简体   繁体   English

python中txt文件的打印行在打印时创建换行

[英]Print line of a txt file in python create break line when print

i'm new to python and i'm trying read every line of a simple txt file, but when print out the result in the terminal, between every line there is an empty line that in the txt file doesn't exist and i have use strip() method to avoid that line, this is the code: 我是python的新手,正在尝试读取简单txt文件的每一行,但是当在终端中打印出结果时,每一行之间都有一个空行,该行在txt文件中不存在,我有使用strip()方法避免出现该行,这是代码:

ins = open( "abc.txt", "r" )
array = []
for line in ins:
    array.append( line )
ins.close()

for riga in array:
    if line.strip() != '':
        print riga

this is the txt file: 这是txt文件:

a
b
c

and this is the result in the terminal: 这是终端中的结果:

a

b

c

i can't understand why create that empty line between a,b,c, any idea? 我不明白为什么要在a,b,c之间建立一条空白线,任何想法?

Because everything in a text file is a character, so when you see something like: 因为文本文件中的所有内容都是字符,所以当您看到类似以下内容的内容时:

a
b
c

Its actually a\\nb\\nc\\n , \\n means new line, and this is the reason why you're getting that extra space. 实际上 a\\nb\\nc\\n\\n表示换行,这就是为什么要获得额外空间的原因。 If you'd like to print everything in the text file into the output console just the way it is, I would fix your print statement like so: 如果您想按原样将文本文件中的所有内容打印到输出控制台中,我将按照以下方式修复您的print语句:

print riga,

This prevents the addition of an extra new line character, \\n . 这样可以防止添加额外的换行符\\n

This should be: 应该是:

for riga in array:
    if line.strip() != '':
        print riga

This: 这个:

for riga in array:
    if riga.strip() != '':     # <= riga here not line 
        print riga.strip()     # Print add a new line so strip the stored \n

Or better yet: 或者更好:

array = []
with open("abc.txt") as ins:
    for line in ins
        array.append(line.strip())

for line in array:
    if line:
        print line

When you run line.strip() != '' , I don't think this is doing what you expect. 当您运行line.strip() != '' ,我认为这并没有达到您的期望。

  • It calls the strip() string method on line which will be the last line of the file since you have already iterated over all of the line s in the previous for loop, leaving the line variable assigned to the last one. 它在line上调用strip()字符串方法,这将是文件的最后一行,因为您已经遍历了上一个for循环中的所有line s,而将line变量分配给了最后一个。
  • It then checks if the returned stripped string from line is not equal to '' . 然后,它检查从line返回的剥离字符串是否不等于''
  • If that condition is met, it prints riga . 如果满足该条件,则打印riga

You need to run strip() on the string you want to print then either store the result or print it right away, and why not do it all in one for loop like this: 您需要在要打印的字符串上运行strip() ,然后存储结果或立即将其打印出来,为什么不将其全部放入for循环中,如下所示:

array = []
with open("abc.txt", "r") as f:
    for line in f:
       array.append(line.strip())
       print(array[-1]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM