你如何附加到 Python 中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4706499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you append to a file in Python?
提问by
How do you append to the file instead of overwriting it? Is there a special function that appends to the file?
你如何附加到文件而不是覆盖它?是否有附加到文件的特殊函数?
采纳答案by Petter
with open("test.txt", "a") as myfile:
myfile.write("appended text")
回答by sinelaw
You need to open the file in append mode, by setting "a" or "ab" as the mode. See open().
您需要通过将“a”或“ab”设置为模式,以追加模式打开文件。请参阅open()。
When you open with "a" mode, the write position will alwaysbe at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file!).
当您以“a”模式打开时,写入位置将始终位于文件的末尾(附加)。您可以使用“a+”打开以允许读取、向后查找和读取(但所有写入仍将位于文件末尾!)。
Example:
例子:
>>> with open('test1','wb') as f:
f.write('test')
>>> with open('test1','ab') as f:
f.write('koko')
>>> with open('test1','rb') as f:
f.read()
'testkoko'
Note: Using 'a' is not the same as opening with 'w' and seeking to the end of the file - consider what might happen if another program opened the file and started writing between the seek and the write. On some operating systems, opening the file with 'a' guarantees that all your following writes will be appended atomically to the end of the file (even as the file grows by other writes).
注意:使用 'a' 与使用 'w' 打开并查找到文件末尾不同 - 考虑如果另一个程序打开文件并开始在查找和写入之间写入会发生什么。在某些操作系统上,使用“a”打开文件可确保您随后的所有写入操作都将自动附加到文件末尾(即使文件因其他写入操作而增长)。
A few more details about how the "a" mode operates (tested on Linux only). Even if you seek back, every write will append to the end of the file:
关于“a”模式如何运行的更多细节(仅在 Linux 上测试)。即使你回溯,每次写入都会附加到文件的末尾:
>>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session
>>> f.write('hi')
>>> f.seek(0)
>>> f.read()
'hi'
>>> f.seek(0)
>>> f.write('bye') # Will still append despite the seek(0)!
>>> f.seek(0)
>>> f.read()
'hibye'
In fact, the fopenmanpagestates:
实际上,fopen联机帮助页指出:
Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded the call:
fseek(stream, 0, SEEK_END);
在追加模式下打开文件(a 作为模式的第一个字符)会导致对该流的所有后续写入操作发生在文件末尾,就像在调用之前一样:
fseek(stream, 0, SEEK_END);
Old simplified answer (not using with):
旧的简化答案(不使用with):
Example: (in a real program use withto close the file- see the documentation)
示例:(在实际程序中用于with关闭文件- 请参阅文档)
>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'
回答by istruble
You probably want to pass "a"as the mode argument. See the docs for open().
您可能希望"a"作为 mode 参数传递。请参阅open()的文档。
with open("foo", "a") as f:
f.write("cool beans...")
There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a"is your best bet.
用于更新 (+)、截断 (w) 和二进制 (b) 模式的模式参数还有其他排列,但从 just 开始"a"是您最好的选择。
回答by Seth Connell
I always do this,
我总是这样做,
f = open('filename.txt', 'a')
f.write("stuff")
f.close()
It's simple, but very useful.
这很简单,但非常有用。
回答by travelingbones
Here's my script, which basically counts the number of lines, then appends, then counts them again so you have evidence it worked.
这是我的脚本,它基本上计算行数,然后附加,然后再次计算它们,以便您有证据表明它有效。
shortPath = "../file_to_be_appended"
short = open(shortPath, 'r')
## this counts how many line are originally in the file:
long_path = "../file_to_be_appended_to"
long = open(long_path, 'r')
for i,l in enumerate(long):
pass
print "%s has %i lines initially" %(long_path,i)
long.close()
long = open(long_path, 'a') ## now open long file to append
l = True ## will be a line
c = 0 ## count the number of lines you write
while l:
try:
l = short.next() ## when you run out of lines, this breaks and the except statement is run
c += 1
long.write(l)
except:
l = None
long.close()
print "Done!, wrote %s lines" %c
## finally, count how many lines are left.
long = open(long_path, 'r')
for i,l in enumerate(long):
pass
print "%s has %i lines after appending new lines" %(long_path, i)
long.close()
回答by K.Suthagar
when we using this line open(filename, "a"), that aindicates the appending the file, that means allow to insert extra data to the existing file.
当我们使用这一行时open(filename, "a"),a表示追加文件,这意味着允许向现有文件插入额外的数据。
You can just use this following lines to append the text in your file
您可以使用以下几行将文本附加到文件中
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
回答by Cleve Green
Python has many variations off of the main three modes, these three modes are:
Python 对主要的三种模式有很多变化,这三种模式是:
'w' write text
'r' read text
'a' append text
So to append to a file it's as easy as:
因此,要附加到文件中,就像这样简单:
f = open('filename.txt', 'a')
f.write('whatever you want to write here (in append mode) here.')
Then there are the modes that just make your code fewer lines:
然后是使您的代码行数更少的模式:
'r+' read + write text
'w+' read + write text
'a+' append + read text
Finally, there are the modes of reading/writing in binary format:
最后,还有二进制格式的读/写模式:
'rb' read binary
'wb' write binary
'ab' append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary
回答by nima moradi
if you want to append to a file
如果你想附加到一个文件
with open("test.txt", "a") as myfile:
myfile.write("append me")
We declared the variable myfileto open a file named test.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
我们声明了变量myfile来打开一个名为test.txt. Open 接受 2 个参数,我们要打开的文件和一个字符串,表示我们要对文件执行的权限或操作的种类
here is file mode options
这是文件模式选项
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)
回答by Primusa
You can also open the file in r+mode and then set the file position to the end of the file.
您也可以在r+模式下打开文件,然后将文件位置设置为文件末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
Opening the file in r+mode will let you write to other file positions besides the end, while aand a+force writing to the end.
打开文件r+模式将让你写,除了年底其他文件的位置,而a和a+力书写到最后。
回答by Alec Alameddine
The 'a'parameter signifies append mode. If you don't want to use with openeach time, you can easily write a function to do it for you:
该'a'参数表示追加模式。如果你不想with open每次都使用,你可以很容易地编写一个函数来为你做:
def append(txt='\nFunction Successfully Executed', file):
with open(file, 'a') as f:
f.write(txt)
If you want to write somewhere else other than the end, you can use 'r+'?:
如果你想写除结尾以外的其他地方,你可以使用'r+'? :
import os
with open(file, 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
Finally, the 'w+'parameter grants even more freedom. Specifically, it allows you to create the file if it doesn't exist, as well as empty the contents of a file that currently exists.
最后,'w+'参数授予更多的自由。具体来说,它允许您创建不存在的文件,以及清空当前存在的文件的内容。

