Cases
The code is as follows |
Copy Code |
filename = raw_input (' Enter your file name ') #输入要遍历读取的文件路径及文件名 FILE = open (filename, ' R ') Done = 0 While does not do: ALine = File.readline () if (ALine!= '): Print ALine, Else Done = 1 File.close () #关闭文件 |
The above is what we often see by line traversing a file method, and you may have noticed the if (aLine!= ') I wrote in the code: part. When ReadLine reads to be empty, it means reading the end of the file. This time, the problem is here, many people will think, is not encountered a blank line, will also be considered as the end of the file? This introduces the question of the title.
In fact, a blank row of files does not return a blank line. Because there is one or more delimiters at the end of each line, the blank line will have at least one line break or other symbol used by the system. So, even if the file really contains a "blank line", the read line is not empty, which means that the program actually does not stop until the actual traversal is read to the end of the file.
ReadLine () and. ReadLines () are very similar. They are all used in structures similar to the following:
Python. ReadLines ()
Example
The code is as follows |
Copy Code |
FH = open (' C:\autoexec.bat ') For line in Fh.readlines (): Print Line
|
The difference between ReadLine () and. ReadLines () is that the latter reads the entire file at once, like. Read (). ReadLines () automatically analyzes the contents of the file into a list of rows that can be used by Python for ... Structure for processing. On the other hand,. ReadLine () reads only one row at a time, usually much slower than. ReadLines (). You should use the. ReadLine () only if there is not enough memory to read the entire file at once.
ReadLines return row count problem
The official document is written as If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling the approximately s Izehint bytes (possibly after rounding up to a internal buffer size) are read.
It is indeed a specified size and will be affected by the internal buffer size up to the internal buffer size. The internal buffer is about 8k. Every time I test the file size is a multiple of 8k (8192)
code is as follows |
copy code |
#!/usr/bin /env python F=open (' a.txt '). ReadLines (1) Open (' B.txt ', ' W '). Writelines (f) Open (' C.txt ', ' W '). Writelines (Open (' a.txt '). ReadLines) Open (' D.txt ', ' W '). Writelines (Open (' a.txt '). ReadLines (9200)) Open (' E.txt ', ' W '). Writelines (Open (' a.txt '). ReadLines (26000)) Open (' F.txt ', ' W '). Writelines (Open (' a.txt '). ReadLines (40000)) |