我有一个文本文件,每行都有一个数字值,我试图将所有值压缩到一行,并在它们之间留一个空格。这是我到目前为止所做的,但它不起作用:
for line in f1:
line = line.rstrip('\n')
f2.write(line)
f1.close()
f2.close()
答案 0 :(得分:3)
只需打印它们之间的空格:
...
for i, line in enumerate(f1):
space = " " if i != 0 else ""
line = line.rstrip('\n')
f2.write(space + line)
f1.close()
f2.close()
如果文件不是巨大的(即它们适合内存),更简单的方法是:
with open("foo") as f1, open("bar", 'w') as f2:
f2.write(" ".join(line.rstrip('\n') for line in f1))
答案 1 :(得分:1)
如果您使用的是Python 2.7+或Python 3.x,并且文件的大小并不过高,那么您可以在内存中执行此操作:
with open(filename1, 'r') as fin, open(filename2, 'w+') as fout:
lines = fin.readlines()
cleaned = [line.strip() for line in lines]
joined = ' '.join(cleaned)
fout.write(joined)
答案 2 :(得分:0)
这样做:
with open("f1", "r") as f1:
with open("f2", "w") as f2:
f2.write(" ".join(map(lambda x: x.strip("\n"), f1.readlines())))
从f1中取出所有行,删除“\ n”,用" "
连接它们并将该字符串写入新文件。