如何追加到文件而不是覆盖它?
当前回答
有时,初学者会遇到这个问题,因为他们试图在循环中打开和写入文件:
for item in my_data:
with open('results.txt', 'w') as f:
f.write(some_calculation(item))
问题是,每次打开文件进行写入时,它都会被截断(清除)。
我们可以通过以追加模式打开来解决这个问题;但在这种情况下,通常最好通过颠倒逻辑来解决问题。如果文件只打开一次,那么每次都不会被覆盖;并且只要它是打开的,我们就可以继续写它——我们不必在每次写的时候都重新打开它(Python这样做是没有意义的,因为它会增加所需的代码而没有好处)。
因此:
with open('results.txt', 'w') as f:
for item in my_data:
f.write(some_calculation(item))
其他回答
您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
以r+模式打开文件将允许您写入除结尾之外的其他文件位置,而a和a+强制写入结尾。
Python有三种主要模式的多种变体,这三种模式是:
'w' write text
'r' read text
'a' append text
因此,要附加到文件,很简单:
f = open('filename.txt', 'a')
f.write('whatever you want to write here (in append mode) here.')
还有一些模式只会使代码行数更少:
'r+' read + write text
'w+' read + write text
'a+' append + read text
最后,有两种二进制格式的读/写模式:
'rb' read binary
'wb' write binary
'ab' append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary
当我们使用这行open(文件名,“a”)时,a表示附加文件,这意味着允许向现有文件插入额外的数据。
您可以使用以下行将文本附加到文件中
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
在文件末尾附加更多文本的最简单方法是使用:
with open('/path/to/file', 'a+') as file:
file.write("Additions to file")
file.close()
open(…)语句中的a+指示以追加模式打开文件,并允许读取和写入访问。
使用完file.close()关闭打开的所有文件也是一个很好的做法。
如果要附加到文件
with open("test.txt", "a") as myfile:
myfile.write("append me")
我们声明了变量myfile以打开名为test.txt的文件。open有两个参数,一个是要打开的文件,另一个是表示要对该文件执行的权限或操作类型的字符串
以下是文件模式选项
Mode Description 'r' This is the default mode. It Opens file for reading. 'w' This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file. 'x' Creates a new file. If file already exists, the operation fails. 'a' Open file in append mode. If file does not exist, it creates a new file. 't' This is the default mode. It opens in text mode. 'b' This opens in binary mode. '+' This will open a file for reading and writing (updating)