消除文件读取Python中的空行

时间:2019-03-18 20:31:12

标签: python

我正在尝试使用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

如何在每次输入后删除空白行?

2 个答案:

答案 0 :(得分:1)

使用以下命令逐行遍历文件时:

for line in aws_envs:

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

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

对比:

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

答案 1 :(得分:0)

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

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