python對資料夾的一些操作

2021-06-02 17:12:28 字數 3048 閱讀 4988

view source

print?

01defcopyfolderos(sfolder,tfolder):

02sourcepath=sfolder

03destpath=tfolder

04forroot, dirs, filesinos.walk(sourcepath):

05

06#figure out where we're going

07dest=destpath+root.replace(sourcepath, '')

08

09#if we're in a directory that doesn't exist in the destination folder

10#then create a new folder

11ifnotos.path.isdir(dest):

12os.mkdir(dest)

13print'directory created at: '+dest

14

15#loop through all files in the directory

16forfinfiles:

17

18#compute current (old) & new file locations

19oldloc=root+'\\'+f

20newloc=dest+'\\'+f

21

22ifnotos.path.isfile(newloc):

23try:

24shutil.copy2(oldloc, newloc)

25print'file '+f+' copied.'

26exceptioerror:

27print'file "'+f+'" already exists'

view source

print?

1def

2forroot, dirs, filesinos.walk(sourcedir):

3forfinfiles:

4os.unlink(os.path.join(root, f))

5fordindirs:

6shutil.rmtree(os.path.join(root, d))

python對檔案,資料夾的一些操作

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。建立檔案 1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 建立目錄 os.mkdir file 建立目錄 複製檔案 shutil.copyfil...

python對檔案及資料夾的一些操作

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。建立檔案 1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 建立目錄 os.mkdir file 建立目錄 複製檔案 shutil.copyfil...

python對檔案及資料夾的一些操作

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。建立檔案 1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 建立目錄 os.mkdir file 建立目錄 複製檔案 shutil.copyfil...