我写了这段代码..但是我无法在行尾附加元素..输出就像这样..
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
关于python - 将列表的每个元素附加到文件行的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500250/