有没有一种方法可以在不以“w”或“a”模式打开文本文件的情况下创建文本文件?例如,如果我想以“r”模式打开一个文件,但该文件不存在,那么当我捕获 IOError 时,我想创建一个新文件 例如:
while flag == True:
try:
# opening src in a+ mode will allow me to read and append to file
with open("Class {0} data.txt".format(classNo),"r") as src:
# list containing all data from file, one line is one item in list
data = src.readlines()
for ind,line in enumerate(data):
if surname.lower() and firstName.lower() in line.lower():
# overwrite the relevant item in data with the updated score
data[ind] = "{0} {1}\n".format(line.rstrip(),score)
rewrite = True
else:
with open("Class {0} data.txt".format(classNo),"a") as src:
src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))
if rewrite == True:
# reopen src in write mode and overwrite all the records with the items in data
with open("Class {} data.txt".format(classNo),"w") as src:
src.writelines(data)
flag = False
except IOError:
print("New data file created")
# Here I want a new file to be created and assigned to the variable src so when the
# while loop iterates for the second time the file should successfully open
最佳答案
一开始只需检查文件是否存在,如果不存在则创建它:
filename = "Class {0} data.txt"
if not os.path.isfile(filename):
open(filename, 'w').close()
从此时起,您可以假设该文件存在,这将大大简化您的代码。
关于python - 在 Python 中创建新的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460951/