简体   繁体   中英

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:

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:

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?

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. 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 riga,

This prevents the addition of an extra new line character, \\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.

  • 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.
  • It then checks if the returned stripped string from line is not equal to '' .
  • If that condition is met, it prints 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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