
仍然使用with open,但是mode参数为a,则当文件不存在时会自动创建,不会报错。
with open("test.txt",mode='a',encoding='utf-8') as ff:
print(ff.readlines())在try块里面使用with open,然后捕获FileNotFoundError,使用os.mknod()函数创建文件,但是只适用于Linux,windows不能使用,因为windows下没有node概念。
import os
try:
with open("test.txt",mode='r',encoding='utf-8') as ff:
print(ff.readlines())
except FileNotFoundError:
os.mknod('test.txt')
print("文件创建成功!")在捕获错误后,使用mode=w方式创建文件。
try:
with open("test.txt",mode='r',encoding='utf-8') as ff:
print(ff.readlines())
except FileNotFoundError:
with open("test.txt", mode='w', encoding='utf-8') as ff:
print("文件创建成功!")不使用try块,使用os.path.exists()方法判断文件是否存在,如果不存在则创建文件。
import os
if os.path.exists('test.txt'):
with open('test.txt',mode='r',encoding='utf-8') as ff:
print(ff.readlines())
else:
with open("test.txt", mode='w', encoding='utf-8') as ff:
print("文件创建成功!")









