简体   繁体   English

如何用文件中的空格替换换行符?

[英]How to replace line-breaks with spaces in a file?

I am reading a file like this:我正在阅读这样的文件:

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())

This is the output:这是 output:

128.0 96.0
191.0 96.0
182.0 136.0
138.0 181.0
186.0 180.0

How can I replace the linebreaks with spaces in every single such file?如何在每个此类文件中用空格替换换行符? I want the file to look like this:我希望文件看起来像这样:

128.0 96.0 191.0 96.0 182.0 136.0 138.0 181.0 186.0 180.0

I know I can use str.replace('\n', ' ') but how can I actually edit the contents of the file line by line?我知道我可以使用str.replace('\n', ' ')但我如何实际逐行编辑文件的内容?

You can still use replace , but you need to f.write after:你仍然可以使用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)

Usually you don't edit a file in-place: you read it and write elsewhere.通常你不会就地编辑文件:你在别处读取它并写入它。 You can then replace the input file with the output once you've succeeded.成功后,您可以将输入文件替换为 output。

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

That being said, for small files and toy examples, you can read in the whole thing and then write it back under the same name:话虽这么说,对于小文件和玩具示例,您可以读入整个内容,然后以相同的名称将其写回:

with open('input.txt', 'rt') as f:
    data = f.read()
with open('input.txt', 'wt') as f:
    f.write(data.replace('\n', ' '))

You can consider using 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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM