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")? ? ? ? ? ? 空目錄、有內容的目錄都可以刪
轉換目錄
os.chdir("path")? ? ? ? ? ? ? ? ? 換路徑
判斷目標
os.path.exists("goal")? ? ? ? ? 判斷目標是否存在
os.path.isdir("goal")? ? ? ? ? ? 判斷目標是否目錄
os.path.isfile("goal")? ? ? ? ? ? 判斷目標是否文件