code Source: Python Reference manual
f = open ("Foo.txt") # Returns a file object
line = F.readline () # Call the ReadLine () method of the file
While line:
Print line, # followed by ', ' will ignore newline characters
# print (line, end = ") # used in Python 3
line = F.readline ()
F.close ()
Can also be written in the following more concise form
For line in open ("Foo.txt"):
Print line,
More detailed file-by-line read operations can be consulted: http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html
1. The most basic way to read files:
?
# file:readline-example-1.py
File = Open ("Sample.txt")
While 1:
line = File.readline ()
If not line:
Break
Pass # do something
It is obviously slower to read data from a file in one row, but it saves memory.
Read the 10M sample.txt file on my machine and read about 32000 lines per second
2. Using the Fileinput module
?
# file:readline-example-2.py
Import Fileinput
For line in Fileinput.input ("Sample.txt"):
Pass
The writing is simple, but after the test found that only 13000 rows of data per second can be read, the efficiency is more than the previous method twice times slower ...
3. File read with cache
?
# file:readline-example-3.py
File = Open ("Sample.txt")
While 1:
lines = File.readlines (100000)
If not lines:
Break
For line in lines:
Pass # do something
Is this method really better? It turns out that with the same data test, it can read 96900 rows of data per second! Efficiency is 3 times times the first method, 7 times times the second method!
————————————————————————————————————————————————————————————
After Python 2.2, we can use a for loop to read each row of data directly on a file object:
?
# file:readline-example-5.py
File = Open ("Sample.txt")
For line in file:
Pass # do something
In Python 2.1, you can only use the Xreadlines iterator to achieve:
?
# file:readline-example-4.py
File = Open ("Sample.txt")
For line in File.xreadlines ():
Pass # do something
Python reads the contents of a file row by line