如何追加文件而不是覆盖它?是否有一个附加到文件的特殊函数?
with open("test.txt","a") as myfile:
myfile.write("appended text")
本教程中的内容可能也很有用。
我注意到许多人正在使用with open(file,"a")方法。我可能有点老土,但是和yanan3相比有什么优势呢?
bluewoodtree:其优点类似于c++中的RAII。如果忘记close(),可能需要一段时间才能真正关闭文件。当代码有多个出口点、异常等等时,您可能会认为很容易忘记它。
print("appended text", file=myfile)对于更熟悉的api也是可能的。
使用codecs.open("test.txt","a","utf-8")支持UTF-8
@DanOsipov在Python3中可以简单地使用open(),默认情况下使用utf-9 !
@Tom:没有。open()不硬编码utf-8。它使用locale.getpreferredencoding(False)。如果知道文件使用utf-8编码,则显式传递encoding="utf-8"参数。
@DanOsipov: io.open()还允许显式传递encoding,但它可能比codecs.open()更好地处理新行。在python3中,它被用作内置的open()。如果只需要支持Python 2.7+,那么使用io.open()而不是codecs.open()。
当作为脚本的一部分运行它时,我得到了语法错误,但是在python控制台中没有运行它。如果我尝试在脚本中运行,它会给我with open(bklist,'a') as myfile: ^ SyntaxError: invalid syntax。如果有帮助,我在while循环中尝试这样做。
使用2.5会引发无效的语法警告:"with"将成为Python 2.6中的保留关键字
@user2015601,与所有RAII一样,如果上下文出现意外退出,清理仍然会发生(例如,如果抛出意外异常)。意外行为可以在调用堆栈的更高位置处理。
如何关闭文件?
这就是with-statement的重点。它在最后关闭文件。
with语句在执行块之前自动调用setup方法(__enter__),在块执行完之后调用teardown方法(__exit__),这样就可以自动关闭文件。更多信息请参见:book. pythontips.com/en/latest/context_manages.html
如果不存在,它会创建一个文件吗?
您需要在追加模式下打开文件,将"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手册说:
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);
旧的简化答案(不使用with):
示例:(在实际程序中使用with关闭文件-请参阅文档)
>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'
所以我只使用file.write()函数,使文件a+/a+b?
您不需要一个close()吗?
@JonasStein,您应该使用with—请参阅docs.python.org/2/whatsnew/2.6.html# peg -343-the- stateme??nt
使用"测试。如果你在windows上写一个文本文件,用txt代替test。
我总是这样做,
f = open('filename.txt', 'a')
f.write("stuff")
f.close()
它很简单,但是非常有用。
用open('filename','a')作为f: f.write('stuff')会更好更安全
a+比a好
它不像前几年发布的大多数答案那么简单,也没有什么用处
@Tim Castelijns有人发布了with语法的替代方法,这很好,如果您在多个位置使用该变量,那么您可能并不总是希望使用with语法。
即使您将f变量传递给其他函数,打开文件的相同函数也应该关闭它。with语法是实现此目的的首选方法。
我有一个类,它持有一个打开的文件句柄。我不能在__init__()中使用with,对吗?也就是说,我已经使用了__enter__()和__exit__(),所以我可以执行with Class() as c: do_stuff()并仍然保持它干净。
@Baldrickk我想说,这当然是一个可以接受的时间显式调用open和close,即在类的__enter__和__exit__方法中。显然,该类本身将与with一起使用。我不反对您的方法,但是,作为一个规则,我们不应该在这里使用答案作为如何编写Python的示例。
@AndyPalmer如此真实。我刚才提到了一个有效的例子,说明什么时候不能直接使用with。
您可能希望传递"a"作为模式参数。有关open(),请参阅文档。
with open("foo","a") as f:
f.write("cool beans...")
对于update(+)、truncating (w)和binary (b)模式,还有其他模式参数的排列,但是最好从"a"开始。
file隐藏一个内置函数。不要把它用于变量。
@MarkTolonen: file不再是Python 3中的内置函数。即使在python2中,也很少使用它。打开文件是一种常见的操作。在Python 2和Python 3上都可以使用file name。知道什么时候不一致。
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
当我们使用这一行open(filename,"a")时,a表示附加文件,这意味着允许向现有文件插入额外的数据。
您可以使用以下几行来在文件中附加文本
def FileSave(filename,content):
with open(filename,"a") as myfile:
myfile.write(content)
FileSave("test.txt","test1
")
FileSave("test.txt","test2
")
您还可以以r+模式打开文件,然后将文件位置设置为文件的末尾。
import os
with open('text.txt', 'r+') as f:
f.seek(0, os.SEEK_END)
f.write("text to add")
以r+模式打开文件将允许您写入文件末尾之外的其他位置,而a和a+强制写入文件末尾。
如果要附加到文件中
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)
这是我的脚本,它基本上是计算行数,然后追加,然后再计算一次,这样你就有了它工作的证据。
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()