我有一个函数,可以在文件的内容中添加一个日期已完成.txt“每次我拜访它并提供日期。功能如下:
def completed(date):
try:
os.chdir(libspath)
os.system("touch completed.txt")
fileobject=open('completed.txt',"r+")
fileobject.write(date+' \n')
fileobject.close()
except:
print "record.completed(): Could not write contents to completed.txt"
其中libspath是文本文件的路径。现在当我调用它说completed('2000.02.16')
时,它将日期写入已完成.txt文件。当我尝试添加另一个日期时,比如说completed('2000.03.18')
,它会覆盖上一个日期,现在文本文件中只有“2000.03.18”,但我希望文件中的两个日期都可用,以便将其用作记录
以
append
模式打开。你应该使用必须以附加模式打开文件:
Python Docs for opening file
“处理文件对象时,最好使用with关键字。这样做的好处是,文件套件完成后会正确关闭,即使在执行过程中引发异常也是如此。它也比写等效的try finally块短得多。”
从Python docs
相关问题 更多 >
编程相关推荐