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

时间:2019-07-28 19:18:43

标签: python string text

我的问题与发现here的问题基本上相同,但是我想使用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))

但这会产生相同的结果。

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

1 个答案:

答案 0 :(得分:0)

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

输出:

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...