Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何附加到文件?_Python_File_Append - Fatal编程技术网

Python 如何附加到文件?

Python 如何附加到文件?,python,file,append,Python,File,Append,如何附加到文件而不是覆盖它?是否有附加到文件的特殊功能?您需要在附加模式下打开文件,方法是将“a”或“ab”设置为模式。看 当您以“a”模式打开时,写入位置将始终位于文件末尾(追加)。您可以使用“a+”打开以允许读取、向后搜索和读取(但所有写入仍将位于文件末尾!) 例如: >>> with open('test1','wb') as f: f.write('test') >>> with open('test1','ab') as f:

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

您需要在附加模式下打开文件,方法是将“a”或“ab”设置为模式。看

当您以“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
声明:

以追加模式打开文件(a作为模式的第一个字符) 导致对该流的所有后续写入操作在 文件结尾,好像在调用之前:

fseek(stream, 0, SEEK_END);

旧的简化答案(不将
一起使用):
示例:(在实际程序中使用
关闭文件
-请参阅)


您可能希望传递
“a”
作为模式参数。有关详细信息,请参阅文档

对于更新(+)、截断(w)和二进制(b)模式,模式参数还有其他排列方式,但最好从a开始。

我总是这样做

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

这很简单,但非常有用。

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

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

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

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

如果要附加到文件中

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) 模式描述 “r”这是默认模式。它打开文件进行读取。 “w”此模式打开文件进行写入。 如果文件不存在,它将创建一个新文件。 如果文件存在,它将截断该文件。 “x”创建一个新文件。如果文件已存在,则操作失败。 “a”在附加模式下打开文件。 如果文件不存在,它将创建一个新文件。 “t”这是默认模式。它以文本模式打开。 “b”以二进制模式打开。 “+”这将打开一个文件进行读写(更新)
您还可以在
r+
模式下打开文件,然后将文件位置设置为文件末尾

import os

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

r+
模式下打开文件将允许您写入结尾以外的其他文件位置,而
a
a+
将强制写入结尾。

参数
'a'
表示附加模式。如果您不想每次在打开时使用
,您可以轻松编写一个函数:

def append(txt='\nFunction Successfully Executed', file):
    with open(file, 'a') as f:
        f.write(txt)
如果您想在结尾以外的其他地方写作,可以使用
'r+'
†:

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



在文件末尾追加更多文本的最简单方法是使用:

with open('/path/to/file', 'a+') as file:
    file.write("Additions to file")
file.close()
open(…)
语句中的
a+
指示以追加模式打开文件,并允许读写访问


使用
file.close()
关闭您使用完后打开的任何文件也是一种很好的做法。

您也可以使用
print
而不是
write

with open('test.txt', 'a') as f:
    print('appended text', file=f)
如果test.txt不存在,则将创建它。

如果有多个进程正在写入文件,则必须使用附加模式,否则数据将被置乱。附加模式将使操作系统将每次写入都放在文件末尾,而不管写入程序认为自己在文件中的位置如何。对于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.
通过使用append模式,操作系统将在文件末尾写入任何内容

import os

with open('text.txt', 'r+') as f:
    f.seek(0, os.SEEK_END)
    f.write("text to add")
f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");
追加most并不表示“打开文件,打开文件后再转到文件末尾一次”。它的意思是,“打开文件,我所做的每一次写入都将在文件的末尾”


警告:要使其正常工作,您必须在一次写入呼叫中一次性写入所有记录。如果您在多次写入之间分割数据,其他写入程序可以也将在您的写入之间进行写入,并损坏您的数据。

文件
隐藏了一个内置函数。不要将其用于变量。@MarkTolonen:
文件
不再是Python 3中的内置项。打开文件是一种常见的操作。在Python2和Python3上都可以使用
file
name。从教程中可能有用。蓝木树:好处类似于在C++中的RAII。如果忘记了close(),则可能需要一段时间才能真正关闭文件。你更容易被解雇
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");