[英]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 ~~ Introductory
和The 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.