Python3 File readline() Method
Overview
readline()The method reads an entire line from the file, including the "\n" character. If a non-negative parameter is specified, it returns the specified number of bytes, including the "\n" character.
Syntax
The syntax of the readline() method is as follows:
fileObject.readline();
Parameters
-
size-- The number of bytes to read from the file.
Return Value
Returns the bytes read from the string.
Example
The following example demonstrates the use of the readline() method:
The content of the file example.txt is as follows:
1:www.example.com 2:www.example.com 3:www.example.com 4:www.example.com 5:www.example.com
Read the content of the file:
Example
#!/usr/bin/python3
# Open the file
fo = open("example.txt", "r+")
print ("File name: ", fo.name)
line = fo.readline()
print ("Read the first line %s" % (line))
line = fo.readline(5)
print ("The read string is: %s" % (line))
# Close the file
fo.close()
# Open the file
fo = open("example.txt", "r+")
print ("File name: ", fo.name)
line = fo.readline()
print ("Read the first line %s" % (line))
line = fo.readline(5)
print ("The read string is: %s" % (line))
# Close the file
fo.close()
The output of the above example is:
文件名为: example.txt 读取第一行 1:www.example.com 读取的字符串为: 2:www
Other Extensions
Python3 File Methods