Skip to main content
 首页 » 编程设计

python之将旧文件中已有换行符的行打印到同一行的新文件中

2024年10月01日7dudu

我希望 newline 在 3 个句子之间只打印一次。但是通过下面的 code,每个句子都打印了 newline 和一个额外的 newline before new index sentence.

with open(convert_file) as infile: 
for line in infile: 
    with open('convert-profile.txt', "a") as f1: 
        if "index" in line: 
            f1.write("\n"+line) 
        elif "scan start time" in line: 
            f1.write(line)   
        elif "binary: [4]" in line: 
            f1.write(line) 
        f1.close 

我猜是因为旧文件 convert_file 中的每个 index、scan time 和 binary 都以一个结尾换行符。 如何将这三个附加到同一 line 并将它们写入新文件?


还有一点,当我使用 "w" 模式进行 print 时,它似乎一直在第一行打印。最后,我得到了一个空白文件。当 "w" 不起作用时,如果我希望它在每次运行 code 时重新写入文件,我应该使用什么模式?

请您参考如下方法:

我建议你先为你要写的行建立一个string,然后再写整行。如果你想删除换行符 character 你应该使用 line.rstrip() 如下:

    line = line.rstrip() 
    result = '' 
    if "index" in line: 
        result += line 
    elif "scan start time" in line: 
        result += line 
    elif "binary: [4]" in line: 
        result += line 
    result += '\n' 

对于模式,with open('convert-profile.txt', 'w') as f1: 应该可以正常工作。