【发布时间】:2015-02-12 04:27:38
【问题描述】:
有没有一种无需在“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
【问题讨论】:
-
这实际上是错误的。但是你可以在linux系统上做到这一点
import os; os.system('touch test.txt') -
啊我想解决办法是在 w 模式下创建一个文件然后关闭它