Python判斷檔案 資料夾存在方法

2022-09-08 06:42:09 字數 1564 閱讀 1778

四種方法:

# 第一種 os.path.exists(file_path)

# 第二種 os.path.isfile(file_path)

# 第三種 pathlib模組

# 第四種 os.access(file_path,mode)

# 第五種 try+open() 或者with open()

示例:

import

osimport

sys#

判斷檔案是否存在

print

(os.getcwd())

#vscode中 python外掛程式不能自動cd到當前目錄

file = os.path.join(sys.path[0],"

test.txt")

#第一種 os.path.exists(file_path)

print("

os.path.exists method test")

print

(os.path.exists(file))

print(os.path.exists("

test1.txt"))

#第二種 os.isfile(file_path)

#這種方法判斷資料夾也是一樣的

print("

os.path.isfile test")

print

(os.path.isfile(file))

print(os.path.isfile("

test1.txt"))

#第三種 pathlib

#python3.4後 內建pathlib模組 pythonp2版本需要安裝

from pathlib import

path

print("

pathlib test")

path =path(file)

print

(path.is_file())

print

(path.exists())

#第四種 os.access(file_path,mode)

"""os.f_ok: 檢查檔案是否存在 0;

os.r_ok: 檢查檔案是否可讀 1;

os.w_ok: 檢查檔案是否可以寫入 2;

os.x_ok: 檢查檔案是否可以執行 3

"""print("

os.access test")

print

(os.access(file,0))

print(os.access("

test.py

",0))

#第五種

#try + open()

#with open()

執行結果:

os.path.exists method test

true

false

os.path.isfile test

true

false

pathlib test

true

true

os.access test

true

false

python判斷檔案或資料夾是否存在

主要涉及的模組是python的os模組 import osos.path.exists 檔名或者資料夾名 判斷是否存在檔案或者資料夾 返回true or false os.path.isfile 檔名或者資料夾名 判斷是否是檔案 返回true or false os.makedirs 資料夾或者路徑...

判斷資料夾是否存在

access函式判斷資料夾或者檔案是否存在 函式原型 int access const char filename,int mode 所屬標頭檔案 io.h filename 可以填寫資料夾路徑或者檔案路徑 mode 0 f ok 只判斷是否存在 2 r ok 判斷寫入許可權 4 w ok 判斷讀取...

C C 判斷檔案 資料夾是否存在

一 判斷資料夾是否存在 1.用createdirectory filemanege null 如果資料夾filemanege不存在,則建立。2.或者if access filemanege 0 1 表示filemanege不存在。3.或者bool pathisdirectory lpctstr ps...