最近,我在尝试用Python制作一个简单的桌面软件,但其中遇见几个小问题想给大家分享一下
一般文件读写都是这样的:
#读取
f = open("./test.txt", 'r')
txt=f.read()
f.close
#写入
with open("./test.txt","w") as f:
f.write("nothing")
f.close
那,有遇见文件不存在,无法读取的情况吗?
如果不怕烦…那就这样:
try:
f = open("./test.txt", 'r')
ds=f.read()
f.close
return ds
except:
with open("./test.txt","w") as f:
f.write("")
f.close
return ""