我正在读取这样的文件:
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path + 'detections/')
landmarks = os.listdir(path + 'landmarks/')
for file in detections:
with open(path + 'detections/' + file, 'r') as f:
print(f.read())
这是输出:
128.0 96.0
191.0 96.0
182.0 136.0
138.0 181.0
186.0 180.0
如何在每个这样的文件中用空格替换换行符?我希望文件看起来像这样:
128.0 96.0 191.0 96.0 182.0 136.0 138.0 181.0 186.0 180.0
我知道我可以使用str.replace('n', ' ')
,但我如何才能逐行编辑文件的内容?
您仍然可以使用replace
,但需要在之后使用f.write
# Open and over-write (r+)
with open("file.txt", 'r+') as f:
x = f.read()
x = x.replace("n", " ")
f.seek(0)
f.write(x)
通常您不会在适当的位置编辑文件:您可以读取文件并在其他位置写入。一旦成功,就可以用输出替换输入文件。
with open('input.txt', 'rt') as fi, open('output.txt', 'wt') as fo:
for line in fi:
fo.write(line.replace('n', ' '))
# optionally move output.txt to input.txt afterward
也就是说,对于小文件和玩具示例,你可以读入整个内容,然后用相同的名称写回:
with open('input.txt', 'rt') as f:
data = f.read()
with open('input.txt', 'wt') as f:
f.write(data.replace('n', ' '))
您可以考虑使用regex:
import re
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path + 'detections/')
landmarks = os.listdir(path + 'landmarks/')
for file in detections:
with open(path + 'detections/' + file, 'w') as f:
f.write(re.sub("n", " ", f.read()))