Python3 從乙個資料夾複製檔案到另乙個資料夾

2022-06-09 20:18:09 字數 1922 閱讀 7351

需求:從input資料夾中隨機獲取一定數量的jpg檔案複製到output資料夾中,

如果input資料夾中有與選中的jpg檔案檔名相同的ans檔案則複製到output資料夾中

**:

1

#!/usr/bin/env python2#

encoding: utf-834

import

os, random, glob

5from shutil import

copyfile67

8#定義要處理的資料夾變數9#

choseimg是隨機選中的jpg檔案檔名包括字尾

10 choseimg =

1112

defcopyfile(inputdir, outdir, count):13#

通過glob.glob來獲取原始路徑下,所有'.jpg'檔案

15#隨機獲取count數量的jpg檔案

16 imagerandom =random.sample(imagelist1, count)

1718

#遍歷所有隨機得到的jpg檔案,獲取檔名稱(包括字尾)

19for item in

imagerandom:

202122#

os.path.splitext(),返回元組,為檔名稱與檔案字尾格式

23for item in

choseimg:24#

將隨機選中的jpg檔案遍歷複製到目標資料夾中

25 copyfile(inputdir+'

/'+item, outdir+'

/'+item)

2627

#更改jpg檔案字尾為ans

28 (temp1, temp2) =os.path.splitext(item)

29 temp = temp1 + '

.ans'30

if os.path.exists(inputdir+'

/'+temp):31#

將ans檔案遍歷複製到目標資料夾中

32 copyfile(inputdir+'

/'+temp, outdir+'

/'+temp)

33return

3435

if__name__ == '

__main__':

36 inputfile = input('

請輸入原始路徑(如:e:/input/):')

37 outfile = input('

請輸入目標路徑(如:e:/output/):')

38 count = int(input('

請輸入隨機選取的數量(如:3):'))

39#指定找到檔案後,另存為的資料夾路徑

40 outdir =os.path.abspath(outfile)41#

指定檔案的原始路徑

42 inputdir =os.path.abspath(inputfile)

43 copyfile(inputdir, outdir, count)

出現的錯誤:

1.inconsistent use of tabs and spaces in indentation

解決辦法:重新調整**縮排,每次縮排都使用8個space

2.沒有判斷ans檔案是否在目錄中存在

增加判斷: if os.path.exists(inputdir+'/'+temp):

Python3建立目錄資料夾

python對檔案的操作還算是方便的,只需要包含os模組進來,使用相關函式即可實現目錄的建立。os.path.exists path 判斷乙個目錄是否存在 os.makedirs path 多層建立目錄 os.mkdir path 建立目錄 引入模組 import os defmkdir path ...

python3 刪除空資料夾

cmd 比較複雜,用python刪除空資料夾,但一時沒有找到符合的 於是自己寫了一點 import osfolder d folder subdir list os.listdir folder for cur dir in subdir list cur path folder cur dir i...

python3 刪除指定資料夾重複檔案

import os import shutil main path r e 指定你要清理重複檔案的根目錄 main file set all file ii 0 while len main path 0 path path main path.pop print path path main di...