如果文件不存在,用r标记打开就报错,w标记就会自动建立新文件。
如果要读取未知是否存在的文件是不是只能这样?
还是有什么其他方法?
- Python code
try: f = open("xx.txt", "r") f.close() except: f = open("xx.txt", "w") f.close() finally: f = open("xx.txt", "r") res = f.readlines() print(len(res)) f.close()
我现在这样做是可以,但是每次都要open close一次文件,会不会不好
------解决方案--------------------
你可以试试a+模式,文件不存在会自动创建,已存在的也可以读取原先内容:
f = open("xx.txt", "a+")
res = f.readlines()
print(len(res))
f.close()