python判斷檔案和資料夾是否存在 建立資料夾

2021-08-02 14:05:00 字數 1063 閱讀 2750

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

import os

os.path.exists(『d:/assist』)

true

os.path.exists(『d:/assist/getteacherlist.py』)

true

os.path.isfile(『d:/assist』)

false

os.path.isfile(『d:/assist/getteacherlist.py』)

true

os.makedirs(『d:/assist/set』)

os.path.exists(『d:/assist/set』)

true

Linux shell判斷檔案和資料夾是否存在

shell判斷檔案,目錄是否存在或者具有許可權 這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi www.2cto.com 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir m...

Linux shell判斷檔案和資料夾是否存在

這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir mypath fi 這裡的 f引數判斷 myfile是否存在 if f my...

python判斷檔案和資料夾是否存在 建立資料夾

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