如何在Python中追加文件?

时间:2011-01-16 16:20:34

标签: python file append

如何附加到文件而不是覆盖它?是否有一个附加到文件的特殊函数?

13 个答案:

答案 0 :(得分:2130)

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

答案 1 :(得分:176)

您需要在附加模式下打开文件,方法是将“a”或“ab”设置为模式。请参阅 open()

当您使用“a”模式打开时,写入位置始终位于文件的末尾(附加)。您可以使用“a +”打开以允许读取,向后搜索和读取(但所有写入仍将位于文件的末尾!)。

示例:

>>> 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'

注意:使用'a'与打开'w'并寻找到文件末尾不同 - 考虑如果另一个程序打开文件并开始在文件之间写入会发生什么寻求和写作。在某些操作系统上,使用“a”打开文件可以保证所有后续写入都将原子地附加到文件末尾(即使文件通过其他写入增长)。


有关“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'

事实上,fopen manpage表示:

  

以附加模式打开文件(作为模式的第一个字符)   导致对此流的所有后续写操作发生在   文件结束,好像在通话之前:

fseek(stream, 0, SEEK_END);

旧的简化答案(不使用with):

示例:(在真实程序中使用with关闭文件 - 请参阅the documentation

>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'

答案 2 :(得分:41)

我总是这样做,

f = open('filename.txt', 'a')
f.write("stuff")
f.close()

这很简单,但非常有用。

答案 3 :(得分:33)

您可能希望将"a"作为模式参数传递。请参阅open()的文档。

with open("foo", "a") as f:
    f.write("cool beans...")

更新(+),截断(w)和二进制(b)模式的模式参数还有其他排列,但从"a"开始是最好的选择。

答案 4 :(得分:25)

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

答案 5 :(得分:14)

您也可以使用print代替write

with open('test.txt', 'a') as f:
    print('appended text', file=f)

如果 test.txt 不存在,它将被创建...

答案 6 :(得分:11)

当我们使用此行open(filename, "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")

答案 7 :(得分:2)

您还可以在validate_email(...)模式下打开文件,然后将文件位置设置为文件末尾。

validate_password(...)

import pandas as pd data = pd.read_csv('output2.csv') data.to_json(''output2.json') 模式打开文件将使您可以写入除末尾之外的其他文件位置,而r+import os with open('text.txt', 'r+') as f: f.seek(0, os.SEEK_END) f.write("text to add") 则强制写入末尾。

答案 8 :(得分:1)

如果要附加到文件

with open("test.txt", "a") as myfile:
    myfile.write("append me")

我们声明了变量myfile以打开名为test.txt的文件。 Open带有2个参数,一个是我们要打开的文件,另一个是代表我们要对该文件执行的权限或操作类型的字符串

这是文件模式选项

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)

答案 9 :(得分:1)

'a'参数表示追加模式。如果您不想每次都使用with open,则可以轻松编写一个函数来帮您:

def append(txt='\nFunction Successfully Executed', file):
    with open(file, 'a') as f:
        f.write(txt)

如果您想写结尾以外的其他地方,可以使用'r+'

import os

with open(file, 'r+') as f:
    f.seek(0, os.SEEK_END)
    f.write("text to add")

最后,'w+'参数赋予了更大的自由度。具体来说,它允许您创建文件(如果不存在)以及清空当前存在的文件的内容。


Credit for this function goes to @Primusa

答案 10 :(得分:0)

将更多文本附加到文件末尾的最简单方法是使用:

with open('/path/to/file', 'a+') as file:
    file.write("Additions to file")
file.close()

a+语句中的open(...)指示以附加模式打开文件并允许读写访问。

使用file.close()关闭使用过的所有文件也是一种很好的做法。

答案 11 :(得分:0)

如果多个进程正在写入文件 ,则必须使用附加模式,否则数据将被加密。追加模式将使操作系统将每次写入都放置在文件末尾,而不管编写者认为他在文件中的位置如何。对于nginx或apache等多进程服务来说,这是一个常见问题,其中同一进程的多个实例正在写入同一日志 文件。考虑一下如果尝试寻找会发生什么,然后写下:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

通过使用附加模式,操作系统会将所有写入操作放在文件末尾。

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

添加最多不是不是,意思是“打开文件,打开文件后转到文件末尾”。意思是,“打开文件,我每次写操作都将在文件末尾。”

警告:要执行此操作,必须将所有记录一次写入一个调用中。如果您在多次写入之间分配数据,其他写入者可以并且将在您之间进行写入,并破坏您的数据。

答案 12 :(得分:-6)

这是我的脚本,它基本上计算行数,然后追加,然后重新计算它们,以便你有证据证明它有效。

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()