0

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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 lines 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]) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.