如何在Python中添加文件?

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


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


您需要在追加模式下打开文件,将"a"或"ab"设置为模式。看到open ()。

当您以"a"模式打开时,写入位置始终位于文件的末尾(追加)。您可以使用"a+"打开以允许读取、向后查找和读取(但是所有的写操作仍然位于文件的末尾!)

例子:

1
2
3
4
5
6
7
>>> 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上测试)。即使你往回找,每次写都会追加到文件的末尾:

1
2
3
4
5
6
7
8
9
10
>>> 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手册说:

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:

1
fseek(stream, 0, SEEK_END);

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

示例:(在实际程序中使用with关闭文件-请参阅文档)

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


我总是这样做,

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

它很简单,但是非常有用。


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

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

对于update(+)、truncating (w)和binary (b)模式,还有其他模式参数的排列,但是最好从"a"开始。


Python在主要的三种模式之外有很多变化,这三种模式是:

1
2
3
'w'   write text
'r'   read text
'a'   append text

因此,添加到文件中很简单:

1
2
f = open('filename.txt', 'a')
f.write('whatever you want to write here (in append mode) here.')

还有一些模式可以让你的代码行数更少:

1
2
3
'r+'  read + write text
'w+'  read + write text
'a+'  append + read text

最后,还有二进制格式的读/写模式:

1
2
3
4
5
6
'rb'  read binary
'wb'  write binary
'ab'  append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary

当我们使用这一行open(filename,"a")时,a表示附加文件,这意味着允许向现有文件插入额外的数据。

您可以使用以下几行来在文件中附加文本

1
2
3
4
5
6
7
8
def FileSave(filename,content):
    with open(filename,"a") as myfile:
        myfile.write(content)

FileSave("test.txt","test1
"
)
FileSave("test.txt","test2
"
)


您还可以以r+模式打开文件,然后将文件位置设置为文件的末尾。

1
2
3
4
5
import os

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

r+模式打开文件将允许您写入文件末尾之外的其他位置,而aa+强制写入文件末尾。


如果要附加到文件中

1
2
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)

这是我的脚本,它基本上是计算行数,然后追加,然后再计算一次,这样你就有了它工作的证据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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()