正在覆盖的文件内容

2024-10-04 03:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,可以在文件的内容中添加一个日期已完成.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”,但我希望文件中的两个日期都可用,以便将其用作记录


Tags: 文件函数功能txt内容dateosdef
2条回答
fileobject=open('completed.txt',"a") 

                                 ^^

append模式打开。你应该使用

with open("completed.txt", "a") as myfile:
    myfile.write(date+' \n')

必须以附加模式打开文件:

fileobject = open('completed.txt', 'a')

Python Docs for opening file

“处理文件对象时,最好使用with关键字。这样做的好处是,文件套件完成后会正确关闭,即使在执行过程中引发异常也是如此。它也比写等效的try finally块短得多。”

Python docs

with open('completed.txt', 'a') as fileobject:
    fileobject.write(date + ' \n')

相关问题 更多 >