繁体   English   中英

如何删除换行符,但在文本文件中保留空白行?

[英]How to remove newlines but keep blank ones in a text file?

我的问题与此处发现的问题基本相同,但我想使用python 3执行该操作。文件中的文本如下所示:

'''
Chapter One ~~ Introductory


The institution of a leisure class is found in its best development at
the higher stages of the barbarian culture; as, for instance, in feudal...
'''

根据我发现的众多建议,我尝试了:

with open('veblen_txt_test.txt', 'r') as src:
    with open('write_new.txt', 'w') as dest:
       for line in src:
           if len(line) > 0:
               line = line.replace('\n', ' ') 
               dest.write(line)
           else:
               line = line + '\n\n'
               dest.write('%s' % (line))

但这返回:

'''
Chapter One ~~ Introductory  The institution of a leisure class is found in its best development at the higher stages of the barbarian culture; as, for instance, in feudal...
'''

预期的输出是:

'''
Chapter One ~~ Introductory  


The institution of a leisure class is found in its best development at the higher stages of the barbarian culture; as, for instance, in feudal...
'''

我试过使用rstrip()

with open('veblen_txt_test.txt', 'r') as src:
    with open('write_new.txt', 'w') as dest:
       for line in src:
           if len(line) > 0:
               line = line.rstrip('\n') 
               dest.write('%s%s' % (line, ' '))
           else:
               line = line + '\n\n'
               dest.write('%s' % (line))

但这会产生相同的结果。

大部分在线答复都是删除空格,而不是保留空格; 我毫不怀疑,解决方案很简单,但是我花了大约一个半小时的时间来尝试上述代码的各种变体,然后才想问问社区。 谢谢你的协助!

如果我们将len(line) > 0更改为len(line) > 1 ,它将完成工作。 这是因为\\n算作1个字符。 您还必须删除此行: line = line + '\\n\\n'因为它会增加4条额外的行(因为在Chapter One ~~ IntroductoryThe institution...之间有两个\\n

输出:

Chapter One ~~ Introductory 

The institution of a leisure class is found in its best development at the higher stages of the barbarian culture; as, for instance, in feudal... 

暂无
暂无

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

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