有沒有在「w」或「a」模式下創建文本文件而不打開文本文件的方法?舉例來說,如果我想打開「R」模式下的文件,但該文件不存在,那麼當我趕上IO錯誤我想要一個新的文件被創建 如:在Python中創建新的文本文件?
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
http://stackoverflow.com/questions/10978869/safely-create-a-file-if-and-only-if-it-does-not-exist-with-python檢查出來 – aerokite 2014-12-13 16:20:27
這實際上是錯誤的。但是你可以在linux系統的'輸入操作系統; os.system('touch test.txt')' – 2014-12-13 16:21:46
ahh我想解決的辦法是在w模式下創建一個文件,然後關閉它 – joyalrj22 2014-12-13 16:31:55