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

2022-07-13 13:00:14 字數 1017 閱讀 8835

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")    判斷目標是否檔案

Python 對檔案及資料夾的操作

檔案 資料夾的移動 複製 刪除 重新命名 匯入shutil模組和os模組 import shutil,os 複製單個檔案 shutil.copy c a 1.txt c b 複製並重命名新檔案 shutil.copy c a 2.txt c b 121.txt 複製整個目錄 備份 shutil.co...

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...