Python之檔案操作

2021-09-09 02:14:46 字數 571 閱讀 2588

github:

1.獲得資料夾下所有檔名

for file in os.listdir(imagedir):

file_path = os.path.join(imagedir, file) 

if os.path.isfile(file_path) and os.path.splitext(file_path)[1]=='.rmvb':

print file

2.判斷資料夾是否存在,如果不存在則建立,如果存在則刪除後建立

outdir = "outdir";

if os.path.isdir(outdir):

shutil.rmtree(outdir)

os.mkdir(outdir)

3.判斷檔案是否存在

import os 

os.path.isfile('test.txt') #如果不存在就返回false 

4.複製檔案

def copyfile(source, target):

open(target, "wb").write(open(source, "rb").read())

Python之檔案操作

file open filename,mode mode預設為 r 例如file ope test.txt r 以讀的方式開啟檔案.檔案操作完畢記得關閉.file.close 其中,mode可以有以下選擇 檔案test.txt的內容為 11111111111 aaaaaaaaa 2222222222...

Python之檔案操作

使用open w 以寫入模式開啟,如果檔案存在將會刪除裡面的所有內容,然後開啟這個檔案進行寫入 a 以追加模式開啟,寫入到檔案中的任何資料將自動新增到末尾 fobj open home coder documents obama.txt 唯讀開啟 fobj fobj.close 關閉檔案 fobj ...

Python之檔案操作

建立目錄import os import errno defmkdir dir try os.makedirs dir except oserror as exc if exc.errno errno.eexist print the dir has been existed pass else r...