Python3 判斷檔案和檔案夾是否存在、建立檔案夾
python中對檔案、檔案夾的操作需要涉及到os子產品和shutil子產品。
建立檔案:
1) os.mknod(“test.txt”) 建立空檔案
2) open(“test.txt”,w) 直接打開一個檔案,如果檔案不存在則建立檔案
建立目錄:
os.mkdir(“file”) 建立目錄
複制檔案:
shutil.copyfile(“oldfile”,”newfile”) oldfile和newfile都隻能是檔案
shutil.copy(“oldfile”,”newfile”) oldfile隻能是檔案夾,newfile可以是檔案,也可以是目标目錄
複制檔案夾:
shutil.copytree(“olddir”,”newdir”) olddir和newdir都隻能是目錄,且newdir必須不存在
重命名檔案(目錄)
os.rename(“oldname”,”newname”) 檔案或目錄都是使用這條指令
移動檔案(目錄)
shutil.move(“oldpos”,”newpos”)
删除檔案
os.remove(“file”)
删除目錄
os.rmdir(“dir”) 隻能删除空目錄
shutil.rmtree(“dir”) 空目錄、有内容的目錄都可以删