将每个列表元素附加到文件行的末尾

时间:2015-12-28 20:25:15

标签: python list file

我写了这段代码..但是我不能在行尾添加元素..输出就是这样..

file:  AGA ABA
       ABA ATA 
       ACA ARA

alist=[1,2,3]

def write_file():
    for item in alist:
        in_file_with_append_mode.write(str(item) + "\n")

in_file_with_append_mode=open("file.txt","a")
write_file()

the output is:

AGA ABA
ABA ATA
ACA ARA
1
2 
3

expected output:
AGA ABA  1 
ABA ATA  2
ACA ARA  3

我的代码需要哪些更改?

1 个答案:

答案 0 :(得分:2)

如果不移动其他数据,则无法附加到文件中的行。

如果您可以将整个文件粘贴到内存中,可以通过重写文件来轻松完成太多麻烦:

alist=[1,2,3]

# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    # Make new lines
    newlines = ['{} {}\n'.format(old.rstrip('\n'), toadd) for old, toadd in zip(f, alist)]
    f.seek(0)  # Go back to beginning for writing
    f.writelines(newlines)  # Write new lines over old
    f.truncate()  # Not needed here, but good habit if file might shrink from change

如果alist的行数和长度不同(它会丢弃行),这将无法正常工作;您可以使用itertools.zip_longest(Py2上的izip_longest)为任一方使用填充值,或使用itertools.cycle重复其中一个输入以匹配。

如果文件不适合内存,则需要将fileinput.inputinplace=True一起使用,或者通过将新内容写入tempfile.NamedTemporaryFile然后替换来手动执行类似的方法带有tempfile的原始文件。

更新:评论要求使用不含zipstr.format的版本;这在行为上是相同的,只是更慢/更少Pythonic并避免zip / str.format

# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    lines = list(f)
    f.seek(0)
    for i in range(min(len(lines), len(alist))):
        f.write(lines[i].rstrip('\n'))
        f.write(' ')
        f.write(str(alist[i]))
        f.write('\n')
    # Uncomment the following lines to keep all lines from the file without
    # matching values in alist
    #if len(lines) > len(alist):
    #    f.writelines(lines[len(alist):])
    f.truncate()  # Not needed here, but good habit if file might shrink from change
相关问题