【问题标题】:Eliminate blank lines in file read Python [duplicate]消除文件读取Python中的空白行[重复]
【发布时间】:2019-03-18 20:31:11
【问题描述】:

我正在尝试使用 Python 将文件读入列表。但是当我这样做时,列表会在每个条目后出现空行。源文件没有那个!

我的代码:

aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
    with open(aws_env_list, 'r') as aws_envs:
        for line in aws_envs:
        print(line)

每行在每个条目后打印出一个空行:

company-lab

company-bill

company-stage

company-dlab

company-nonprod

company-prod

company-eng-cis

源文件如下所示:

company-lab
company-bill
company-stage
company-dlab
company-nonprod
company-prod
company-eng-cis

如何去掉每次输入后的空行?

【问题讨论】:

  • 该文件包含换行符 ('\n') 但在您循环时不会删除它们。 print 函数还在末尾打印一个换行符。因此,您要么使用print(line, end='') 从打印函数中删除新行,要么使用line=line.strip() 从行中删除新行。

标签: python


【解决方案1】:

当您使用以下命令逐行迭代文件时:

for line in aws_envs:

line 的值包括行尾字符...和print 命令,默认情况下添加一个行尾字符到您的输出。您可以通过将end 参数设置为空值来抑制这种情况。比较:

>>> print('one');print('two')
one
two

对比:

>>> print('one', end='');print('two')
onetwo

【讨论】:

    【解决方案2】:

    您的文件在每行末尾都有一个换行符,例如:

    company-lab\n
    company-bill\n
    company-stage\n
    company-dlab\n
    company-nonprod\n
    company-prod\n
    company-eng-cis # not here though this has an EOF (end-of-file) character.
    

    因此,您对print(line) 的电话将在打印中包含这些内容!您可以避免这种情况:

    aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
    with open(aws_env_list, 'r') as aws_envs:
        for line in aws_envs.readlines():
            print(line.strip()) # just strip the \n away!
    

    更新

    如果你想只计算文本而不是换行符,你可以像这样去掉它:

    aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
    with open(aws_env_list, 'r') as aws_envs:
        for line in aws_envs.readlines(): 
            line = line.strip() # You can strip it here and reassign it to the same variable
            # Now all your previous code with the variable 'line' will work as expected
            print(line) # no need to strip again
            do_computations(line) # you can pass it to functions without worry
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多