Python 如何在关闭和打开文件后写入文件的结尾?

Python 如何在关闭和打开文件后写入文件的结尾?,python,file,Python,File,我试图在w+模式下创建一个文件,在其中写入一些数据,打印该日期,关闭文件,重新打开文件,然后再写入一些数据,将其自身附加到已写入的数据中,而不会丢失原始数据。我知道当我第二次打开它时,并没有将它打开到w+模式,但w模式发现了这一点,但我仍然被卡住了 我正在尝试使用.seek(0,2)方法将指针移动到文件末尾,然后写入。这是这里建议的一种方法,似乎大多数人都同意它是有效的。它对我有效,但在尝试关闭和重新打开文件时无效 # open a new file days.txt in write plus

我试图在w+模式下创建一个文件,在其中写入一些数据,打印该日期,关闭文件,重新打开文件,然后再写入一些数据,将其自身附加到已写入的数据中,而不会丢失原始数据。我知道当我第二次打开它时,并没有将它打开到w+模式,但w模式发现了这一点,但我仍然被卡住了

我正在尝试使用.seek(0,2)方法将指针移动到文件末尾,然后写入。这是这里建议的一种方法,似乎大多数人都同意它是有效的。它对我有效,但在尝试关闭和重新打开文件时无效

# open a new file days.txt in write plus read mode 'w+' 

days_file = open('days.txt', "w+")

# write data to file

days_file.write(" Monday\n Tuesday\n Wednesday\n Thursday\n Friday\n")

# use .seek() to move the pointer to the start read data into days

days_file.seek(0)

days = days_file.read()

# print the entire file contents and close the file

print(days)

days_file.close()

# re open file and use .seek() to move the pointer to the end of the file and add days

days_file = open("days.txt", "w")

days_file.seek(0,2)


days_file.write(" Saturday\n Sunday")

days_file.close()

# Re open file in read mode, read the file, print list of both old and new data

days_file = open("days.txt", "r")

days_file.seek(0)


days = days_file.read()


print("My output is: \n",day)

My output is: 
  Saturday
  Sunday
如果我在任何时候都不关闭文件,而只是停留在w+模式下,我就可以让这段代码正常工作,但是,我要搜索的是一种创建+写入+关闭+重新打开+追加的方法。任何解决方案?

使用
file=open(“days.txt”,“a”)
以追加模式打开文件

编辑:

使用
with
关键字打开文件可以安全、一致地关闭文件,即使引发了
异常

with open(myfile, 'w+'):
    # Do things

# File closes automatically here

否则,您必须手动调用
file.close()
。否则,您的文件将保持打开状态,如果您一直在打开文件,您可能会用完句柄

使用附加模式
a
我将利用此机会介绍
,并将
添加到答案中,请参阅编辑