As mentioned in the previous chapter, if you want to read the contents of a file opened with the open function, you can use the readline and readlines functions in addition to the read function.
Unlike the read function, these two functions use "line" as the reading unit, which reads one line in the target file at a time. For reading files opened in text format, reading one line is well understood; for reading files opened in binary format, they will use "\ n" as a sign to read one line.
The readline function is used to read a line in the file, including the last newline character "\ n". The basic syntax of this function is:
file.readline([size])
Among them, file is an open file object; size is an optional parameter used to specify the maximum number of characters (bytes) to be read at a time when each line is read.
As with the read function, the prerequisite for this function to successfully read the file data is that the use of the "Python open function" specifies that the mode of opening the file must be readable (including r, rb, r +, and rb + 4).
Taking the file a.txt created in the previous chapter as an example, the file has the following two lines of data:
Python tutorial:
www.freelearningpoints.com
The following program demonstrates the specific use of the readline function:
f = open ("a.txt") #Read a line of data byt = f.readline () print (byt) #close the file f.close
The output is:
Python tutorial:
Because the readline () function reads the last newline character "\ n" when reading the content of a line in the file, plus the print function outputs a newline by default, so you will see more in the output. A blank line.
Not only that, you can also limit the maximum number of characters (bytes) that can be read when reading line by line, for example:
#Open the specified file in binary form f = open ("a.txt", 'rb') byt = f.readline (6) print (byt) #close the file f.close
The output is:
b'Pytho'
Compared with the output of the previous example, because there is no complete read of one line of data, no newline character will be read.
The readlines function is used to read all the lines in the file. It is similar to calling the read function without specifying the size parameter, except that the function returns a list of strings, where each element is a line in the file.
Like the readline function, the readlines function reads each line with a newline character at the end of the line.
The basic syntax of the readlines function is as follows:
file.readlines()
Where file is an open file object. Like the read and readline functions, it requires that the mode of opening the file must be readable (including r, rb, r +, and rb + 4).
Example:
f = open("a.txt",'rb') byt = f.readlines() print(byt) f.close
The output is:
b'Python tutorial: \r\n', b'www.freelearningpoints.com'
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises