File Object Methods of Reading a Text File:
.read(), .readline() and .readline() methods include the EOL character in the string it reads. To remove the EOL character requires extra string processing, see .strip(), .lstrip(), .rstrip() to remove the EOL or other characters.
Before a file can be read, it first must be opened. See the File Processing note.
.read()read() is a method of a file object. The file object is created by the open() statement.When the read()method is called, it returns some data from the file. If read()is not given a parameter, the entire file is read and placed into the variable that is assigned to it.
If the EOF (End Of File) has been reached, read() will return an empty string "" (or '', either a pair of single or double quotes can be used)
CAUTION: if the file is larger than the amount of memory available on the computer you are using, the program will crash.
Note: To read() a file, it first must be opened
string_variable:
Read an entire file in to a single variable:
Read an entire file in to a single variable removing the EOL characters at the same time:
.readline().readline() is a method of a file object. The file object is created by the open() statement.When the .readline()method is called, it reads one line from a text file. The EOL (End Of Line) is represented by the '\n' character. All lines in a text file contain an EOL character except the last line in the file
If the EOF (End Of File) has been reached, .readline() will return an empty string ""
readline() SyntaxNote: To readline() a file, it first must be opened string_variable = file_object.readline() string_variable:
file_object: the name that will be used in the program to process the file.
readline() ExampleThis is a very traditional method of reading a file. the logic used here is call "priming the loop". The first line of the file is read before the while loop. The while loop checks to see if the EOF has been reached. Providiing the EOF has not been reached the data is processed and another line is read.This method uses an implied readline(). The for statement does the reading and quits when the EOF is reached.
.readlines().readlines() is a method of a file object. The file object is created by the open() statement.When the .readlines()method is called, the entire file is read into a list with each line being one element of the list.
If the EOF (End Of File) has been reached, .readlines() will return an empty string ""
.readlines() SyntaxNote: To .readlines() a file, it first must be openedlistOfStrings_variable = file_object.readlines() listOfString_variable: a list (an array) of strings. Each element in the list contains a string that holds one line from the file.
file_object: the name that will be used in the program to process the file.
.readlines() Example
|