我写了这段代码..但是我不能在行尾追加元素..输出就是这样..
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
我的代码需要哪些更改?
请您参考如下方法:
您不能在不移动其他数据的情况下追加到文件中的行。
如果您可以将整个文件放入内存,则可以通过就地重写文件来太多麻烦地完成此操作:
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.input 与 inplace=True 一起使用,或者通过编写新文件手动执行类似的方法内容到 tempfile.NamedTemporaryFile 然后用临时文件替换原始文件。
更新:评论要求一个没有zip或str.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
