问题:如何在Python中附加文件?

您如何附加到文件而不是覆盖文件?有附加到文件的特殊功能吗?

How do you append to the file instead of overwriting it? Is there a special function that appends to the file?


回答 0

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

回答 1

您需要通过将“ 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 指出:

以追加模式(模式的第一个字符)打开文件会导致对该流的所有后续写入操作在文件末尾发生,就像在调用之前一样:

fseek(stream, 0, SEEK_END);

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

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

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

You need to open the file in append mode, by setting “a” or “ab” as the mode. See open().

When you open with “a” mode, the write position will always be 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!).

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

>>> 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 fopen manpage states:

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

Old simplified answer (not using with):

Example: (in a real program use with to close the file – see the documentation)

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

回答 2

我总是这样做

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

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

I always do this,

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

It’s simple, but very useful.


回答 3

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

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

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

You probably want to pass "a" as the mode argument. See the docs for 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.


回答 4

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

Python has many variations off of the main three modes, these three modes are:

'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

回答 5

当我们使用这一行时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")

when we using this line open(filename, "a"), that a indicates the appending the file, that means allow to insert extra data to the existing file.

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

回答 6

您也可以使用print代替write

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

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

You can also do it with print instead of write:

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

If test.txt doesn’t exist, it will be created…


回答 7

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

import os

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

打开文件r+模式将让你写,除了年底其他文件的位置,而aa+力书写到最后。

You can also open the file in r+ mode and then set the file position to the end of the file.

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 a and a+ force writing to the end.


回答 8

如果要附加到文件

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

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

这是文件模式选项

模式说明

'r'这是默认模式。打开文件进行读取。
'w'此模式打开文件进行写入。 
如果文件不存在,它将创建一个新文件。
如果文件存在,它将截断该文件。
'x'创建一个新文件。如果文件已经存在,则操作失败。
'a'以追加模式打开文件。 
如果文件不存在,它将创建一个新文件。
't'这是默认模式。它以文本模式打开。
'b'以二进制模式打开。
'+'这将打开一个文件,用于读写(更新)

if you want to append to a file

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

We declared the variable myfile to 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

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)

回答 9

'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+'参数赋予了更大的自由度。具体来说,它允许您创建文件(如果不存在)以及清空当前存在的文件的内容。


此功能的功劳归@Primusa

The 'a' parameter signifies append mode. If you don’t want to use with open each time, you can easily write a function to do it for you:

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

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.


Credit for this function goes to @Primusa


回答 10

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

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

a+open(...)声明中指示打开追加模式的文件,允许读取和写入访问。

使用file.close()完后,关闭所有打开的文件也是一种好习惯。

The simplest way to append more text to the end of a file would be to use:

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

The a+ in the open(...) statement instructs to open the file in append mode and allows read and write access.

It is also always good practice to use file.close() to close any files that you have opened once you are done using them.


回答 11

这是我的脚本,基本上计算行数,然后追加,然后再对它们进行计数,这样您就可以证明它起作用了。

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。