关闭并打开文件后,如何写入文件末尾?

时间:2018-08-23 13:23:58

标签: python file

我正在尝试以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 +模式,则可以使此代码正常工作,但是,我正在寻找的是一种创建+编写+关闭+重新打开+追加的方法。有解决方案吗?

1 个答案:

答案 0 :(得分:1)

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

编辑:

即使抛出with,也可以使用Exception关键字打开文件,从而可以安全,一致地关闭文件。

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

# File closes automatically here

否则,您必须手动调用file.close()。否则,您的文件将保持打开状态,并且如果您不断打开文件,则可能用完了句柄

相关问题