我的文本文件包含不同数量的换行符。除了那些之外,我该如何删除新行。
我在文本文件中的数字示例
1
2
3
4
2
如果我open('thefile.txt').read().replace('\n', '')
我将把所有内容都放在一行中。我怎样才能获得这样的输出。
1
2
3
4
2
答案 0 :(得分:1)
我认为最好只删除所有只包含空格的行,然后加入剩余的行:
例如:
with open('thefile.txt') as myfile:
result = '\n'.join([line.strip() for line in myfile if line.strip()])
print(result)
或者,如果您不想strip
两次:
result = '\n'.join([line for line in map(str.strip, myfile) if line])
或使用filter
而不是理解:
result = '\n'.join(filter(bool, map(str.strip, myfile)))
答案 1 :(得分:1)
使用正则表达式并将这些重复出现的内容替换为一个。
>>> import re
>>> text = open('file.txt').read()
>>> text = re.sub(r'\n+', '\n', text)
>>> with open('file2.txt', 'w') as f:
... f.write(text.rstrip())
...
>>>