user2178841
user2178841

Reputation: 859

Combined effect of reading lines twice?

As a practice, I am learning to reading a file.

As is obvious from code, hopefully, I have a file in working/root whatever directory. I need to read it and print it.

my_file=open("new.txt","r")
lengt=sum(1 for line in my_file)
for i in range(0,lengt-1):
    myline=my_file.readlines(1)[0]
    print(myline)

my_file.close()

This returns error and says out of range.

The text file simply contains statements like

line one
line two
line three
.
.
.

Everything same, I tried myline=my_file.readline(). I get empty 7 lines.

My guess is that while using for line in my_file, I read up the lines. So reached end of document. To get same result as I desire, I do I overcome this?

P.S. if it mattersm it's python 3.3

Upvotes: 0

Views: 73

Answers (2)

Mike Müller
Mike Müller

Reputation: 85462

No need to count along. Python does it for you:

my_file = open("new.txt","r")
for myline in my_file:
    print(myline)

Details:

my_file is an iterator. This a special object that allows to iterate over it.

You can also access a single line:

line 1 = next(my_file)

gives you the first line assuming you just opened the file. Doing it again:

line 2 = next(my_file)

you get the second line. If you now iterate over it:

for myline in my_file:
    # do something

it will start at line 3.

Stange extra lines?

 print(myline)

will likely print an extra empty line. This is due to a newline read from the file and a newline added by print(). Solution:

Python 3:

print(myline, end='')

Python 2:

print myline,  # note the trailing comma.

Playing it save

Using the with statement like this:

with open("new.txt", "r") as my_file:
    for myline in my_file:
        print(myline)
    # my_file is open here
# my_file is closed here

you don't need to close the file as it done as soon you leave the context, i.e. as soon as you continue with your code an the same level as the with statement.

Upvotes: 2

Nick Peterson
Nick Peterson

Reputation: 771

You can actually take care of all of this at once by iterating over the file contents:

my_file = open("new.txt", "r")
length = 0
for line in my_file:
    length += 1
    print(line)
my_file.close()

At the end, you will have printed all of the lines, and length will contain the number of lines in the file. (If you don't specifically need to know length, there's really no need for it!)

Another way to do it, which will close the file for you (and, in fact, will even close the file if an exception is raised):

length = 0
with open("new.txt", "r") as my_file:
    for line in my_file:
        length += 1
        print(line)

Upvotes: 0

Related Questions