"Turn from: Http://www.ibm.com/developerworks/cn/linux/sdk/python/python-5/index.html#N1004E"
When we talk about "text processing," we usually refer to what we are dealing with. Python reads the contents of a text file into a string variable that can be manipulated very easily. The file object provides three "read" methods:. Read (),. ReadLine (), and. ReadLines (). Each method can accept a variable to limit the amount of data that is read each time, but they typically do not use variables. Read () reads the entire file each time, and it is typically used to place the contents of the file into a string variable. however. Read () produces the most direct string representation of the file content, but it is not necessary for continuous row-oriented processing and is not possible if the file is larger than the available memory.
. ReadLine () and. ReadLines () are very similar. They are used in structures similar to the following:
Python. ReadLines () example
FH = open (' C:\\autoexec.bat ') fh.readlines (): Line |
The difference between. ReadLine () and. ReadLines () is that the latter reads the entire file one at a time, like. Read (): ReadLines () automatically parses the contents of the file into a list of rows that can be used by Python for ... in ... Structure for processing. On the other hand,. ReadLine () reads only one line at a time, usually much slower than. ReadLines (). You should use. ReadLine () only if there is not enough memory to read the entire file at once.
Read () ReadLine () and ReadLines () usage in Python