Hi guys, i am a beginner with python, (in fact, i started yesterday)
I have some experience with C and CPP. So somethings in python just surprises me(happily, i dont want to say confuses)

#consider there is a file object infile
while 1:
            line=infile.readline();
            if not line: break
            print line

I know that this is a infinite loop which will continously read each line and print it from a file. What surprises me is that how does the readline() function reads the next line every time without any variable for some kind of incrementing. How does it know it should read the line next to the line it read previously.

File method readline() reads an entire line from an open file at the file's current position. The file position is relocated. File method tell() returns the current position. Example:

>>> f = open(r'D:\SDS2_7.0\macro\Work In Progress\line_numbers.txt')
>>> f.tell()
0L
>>> f.readline()
'Line 1\n'
>>> f.tell()
8L
>>> f.readline()
'Line 2\n'
>>> f.tell()
16L

An empty string is returned when the file position is at EOF.

readline reads until it hits a line termination, (\n=decimal 10 in ascii, or \r\n=decimal 13 & 10, depending on the OS). Decimal 26 is generally used in ascii for end of file, which would terminate a file read also. So a byte is read and if it is not a termination character it is stored in a string and another byte is read, etc. We could do this ourselves but it's nice to have these internals handled for us.

...Adding on to the previous posts; another thing to keep in mind is that EVERYTHING in python is an object; meaning that the file handle (object) has methods and members that facilitate line-by-line iteration.

That's funny I remember being completely lost when trying to read files in C++.

Maybe this is less confusing?

file = open('somefile.txt','r')
list = file.readlines()
file.close()

now you have a list of all the lines in the file!

list = file.readlines()

List is a reserved word in python and should not be used as a variable's name. Use something like data_list = file.readlines()

Good to know. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.