Python 从txt文件中删除换行符

Python 从txt文件中删除换行符,python,Python,如果要从以下文本文件中删除换行符: hello there 我使用一个简单的代码如下: with open('words.txt') as text: for line in text: print (line.strip()) 它的输出是: hello there 但是,我希望我的代码输出以下内容: hello there 我该怎么做?提前感谢。如果您只想删除它的换行符,您可以使用string.replace(“\n”,”) 或者如果它只使用carrage返回而不是换行

如果要从以下文本文件中删除换行符:

hello

there
我使用一个简单的代码如下:

with open('words.txt') as text:
  for line in text:
    print (line.strip())
它的输出是:

hello

there
但是,我希望我的代码输出以下内容:

hello
there

我该怎么做?提前感谢。

如果您只想删除它的换行符,您可以使用
string.replace(“\n”,”)

或者如果它只使用carrage返回而不是换行符(*nix),则
string.replace(“\r”,”)


James

添加
if line.strip()=='':在打印
语句之前继续执行

您需要测试一行是否为空才能解决此问题

with open('words.txt') as text:
    for line in text:
        if line:
            print (line.strip())

在python中,空字符串是错误的。也就是说,对空字符串进行if测试将被认为是错误的。

我看到两种方法可以实现您想要的结果

  • 逐行阅读

    with open('bla.txt') as stream:
        for line in stream:
            # Empty lines will be ignored
            if line.strip():
                print(line)
    
  • 阅读所有内容

    import re
    with open('bla.txt') as stream:
        contents = stream.read()
        print re.sub('\s$', '', contents, flags=re.MULTILINE)
    

  • 您是否考虑过测试
    是否为空?要删除空文本行,您可以尝试以下方法