android 判断文件是否存在_每日一课 | Python检查文件是否存在
生活随笔
收集整理的這篇文章主要介紹了
android 判断文件是否存在_每日一课 | Python检查文件是否存在
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在Python中,我們可以使用os.path.isfile()或pathlib.Path.is_file()(Python 3.4)來(lái)檢查文件是否存在。1. pathlibPython 3.4的新功能?from?pathlib import?Path
fname = Path("c:\\test\\abc.txt")
print(fname.exists()) # true
print(fname.is_file()) # true
print(fname.is_dir()) # false
dir = Path("c:\\test\\")
print(dir.exists()) # true
print(dir.is_file()) # false
print(dir.is_dir()) # true如果檢查?from?pathlib import?Path
fname = Path("c:\\test\\abc.txt")if?fname.is_file():
????print("file exist!")else:
????print("no such file!")
fname = "c:\\test\\abc.txt"print(os.path.exists(fname)) # trueprint(os.path.isfile(fname)) # trueprint(os.path.isdir(fname)) # false
dir = "c:\\test\\"print(os.path.exists(dir)) # trueprint(os.path.isfile(dir)) # falseprint(os.path.isdir(dir)) # true如果檢查import?os.path
fname = "c:\\test\\abc.txt"if?os.path.isfile(fname):print("file exist!")else:print("no such file!")
????with open(fname) as?file:for?line?in file:print(line, end='')
except IOError as?e:print(e)輸出量?[Errno 2] No such file?or?directory: 'c:\\test\\no-such-file.txt'
fname = Path("c:\\test\\abc.txt")
print(fname.exists()) # true
print(fname.is_file()) # true
print(fname.is_dir()) # false
dir = Path("c:\\test\\")
print(dir.exists()) # true
print(dir.is_file()) # false
print(dir.is_dir()) # true如果檢查?from?pathlib import?Path
fname = Path("c:\\test\\abc.txt")if?fname.is_file():
????print("file exist!")else:
????print("no such file!")
2. os.path
一個(gè)經(jīng)典的os.path示例import?os.pathfname = "c:\\test\\abc.txt"print(os.path.exists(fname)) # trueprint(os.path.isfile(fname)) # trueprint(os.path.isdir(fname)) # false
dir = "c:\\test\\"print(os.path.exists(dir)) # trueprint(os.path.isfile(dir)) # falseprint(os.path.isdir(dir)) # true如果檢查import?os.path
fname = "c:\\test\\abc.txt"if?os.path.isfile(fname):print("file exist!")else:print("no such file!")
3.試試:除了
我們還可以使用try except檢查文件是否存在。fname = "c:\\test\\no-such-file.txt"try:????with open(fname) as?file:for?line?in file:print(line, end='')
except IOError as?e:print(e)輸出量?[Errno 2] No such file?or?directory: 'c:\\test\\no-such-file.txt'
參考文獻(xiàn)
pathlib —面向?qū)ο蟮奈募到y(tǒng)路徑
os.path —常用路徑名操作
每日一課 | 如何將String轉(zhuǎn)換為int
每日一課 | Python time.sleep 精準(zhǔn)延遲到秒
每日一課 | Python 如何判斷一個(gè)字符串是否包含另一個(gè)字符串?
球分享
球點(diǎn)贊
球在看
總結(jié)
以上是生活随笔為你收集整理的android 判断文件是否存在_每日一课 | Python检查文件是否存在的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言 char转int_图文并茂,一文
- 下一篇: 不畏浮云遮望眼下一句(沾衣欲湿杏花雨下一