消除文件读取Python中的空行
我正在尝试使用Python将文件读入列表。但当我这样做时,列表会在每个条目后显示为空行。源文件没有那个 我的代码:消除文件读取Python中的空行,python,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) 每行在每个条目后打印一个空行:
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
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
<>如何在每次条目后使用“”逐行遍历一个文件?
for line in aws_envs:
line的值包括行尾字符…默认情况下,print命令会将行尾字符添加到输出中。可以通过将“结束”参数设置为空值来抑制该操作。比较:
>>> print('one');print('two')
one
two
Vs:
文件的每行末尾都有一个新行字符,如:
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.
因此,您对printline的调用将这些包含在打印中!您可以通过以下方式避免这种情况:
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!
更新
如果您只想使用文本而不使用换行符进行计算,可以按如下方式将其删除:
company-lab
company-bill
company-stage
company-dlab
company-nonprod
company-prod
company-eng-cis
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
该文件包含换行符“\n”,但在循环时不会删除它们。print函数还可以在末尾打印换行符。因此,您可以使用printline,end=从打印函数中删除新行,或者使用line=line.strip从行中删除新行。