如何在Python中附加文件?

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


#1楼

我总是这样做

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

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


#2楼

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

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

#3楼

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

#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

#5楼

您需要通过将“ 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'

#6楼

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

#7楼

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

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

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


#8楼

如果要附加到文件

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)

#9楼

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

import os

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

r+模式下打开文件将使您可以写入除末尾以外的其他文件位置,而aa+强制写入末尾。


#10楼

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值