首页 文章

你如何附加到文件?

提问于
浏览
1261

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

7 回答

  • 2000

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

    这是我的脚本,它基本上计算行数,然后追加,然后重新计算它们,以便你有证据证明它有效 .

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

    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
    
  • 167
    with open("test.txt", "a") as myfile:
        myfile.write("appended text")
    
  • 35

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

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

    更新(),截断(w)和二进制(b)模式的模式参数还有其他排列,但从 "a" 开始是最好的选择 .

  • 11

    您需要通过将"a"或"ab"设置为模式,以追加模式打开文件 . 见open() .

    当您使用"a"模式打开时,写入位置将 always 位于文件的末尾(附加) . 您可以使用"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'
    

    Note :使用'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 manpage状态:

    以附加模式打开文件(作为模式的第一个字符)会导致对此流的所有后续写入操作都发生在文件结尾处,就像在调用之前一样:fseek(stream,0,SEEK_END);


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

    示例:(在实际程序中 use with to close the file - 请参阅the documentation

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

    我总是这样做,

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

    它很简单,但非常有用 .

相关问题