最近寫python腳本的時候遇到個讀寫文件的問題,當(dāng)我用withopen打開文件讀文件的時候如果文件不存在就會報FileNotFoundError這個錯誤,并且在加入了try之后使用API里面的mknod()函數(shù)創(chuàng)建也不行,經(jīng)過探索,得出幾種讀文件時文件不存在則創(chuàng)建文件的解決辦法。
仍然使用withopen,但是mode參數(shù)為a,則當(dāng)文件不存在時會自動創(chuàng)建,不會報錯。
withopen("test.txt",mode='a',encoding='utf-8')asff:
print(ff.readlines())
在try塊里面使用withopen,然后捕獲FileNotFoundError,使用os.mknod()函數(shù)創(chuàng)建文件,但是只適用于Linux,windows不能使用,因為windows下沒有node概念。
importos
try:
withopen("test.txt",mode='r',encoding='utf-8')asff:
print(ff.readlines())
exceptFileNotFoundError:
os.mknod('test.txt')
print("文件創(chuàng)建成功!")
在捕獲錯誤后,使用mode=w方式創(chuàng)建文件。
try:
withopen("test.txt",mode='r',encoding='utf-8')asff:
print(ff.readlines())
exceptFileNotFoundError:
withopen("test.txt",mode='w',encoding='utf-8')asff:
print("文件創(chuàng)建成功!")
不使用try塊,使用os.path.exists()方法判斷文件是否存在,如果不存在則創(chuàng)建文件。
importos
ifos.path.exists('test.txt'):
withopen('test.txt',mode='r',encoding='utf-8')asff:
print(ff.readlines())
else:
withopen("test.txt",mode='w',encoding='utf-8')asff:
print("文件創(chuàng)建成功!")
以上內(nèi)容為大家介紹了python培訓(xùn)之文件不存在時創(chuàng)建文件,希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。