Python Read File
The read() method is a Python file method that reads the contents of a file and returns a string of the contents of the file.
Related course: Complete Python Programming Course & Exercises
Parameter Description Remarks
- size Reads the number of bytes in the file The positive integer parameter can be omitted. When omitted, the entire document is read in one sitting.
- Reads the file and returns the value of the string type.
You can use these functions:
#Read everything in the text, return string read() #Read only the first line of text, return one string readline() #reads everything in the text and returns list readlines()
read() in Python
Size omitted, read the entire document in one sitting. File to be read demo.txt.
data = open("demo.txt", "r").read() print(data)
Read bytes from file
File to be read: demo.txt. Suppose we want to read only 30 bytes of data.
data = open("demo.txt", "r").read(30) print(data)
File to be read: demo.txt
Reading empty file
The read method returns an empty string when size is equal to 0.
data = open("demo.txt", "r").read(0) print(data) print(type(data)) print(len(data))
<class 'str'>\ 0
read(), readline(), readlines()
In order to distinguish the difference between the read(), readline(), and readlines() functions in python, we use the python instance to see
First create a file /tmp/week.txt that reads.
$ cat /tmp/week.txt Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Then go to the python parser.
[user@linux ~]# python Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>> f=open('/tmp/week.txt','rb') #Open /tmp/week.txt file in read mode >>> f.read() #call the read() function 'Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n' #Back to results >>> f.readline() #call the readline() function 'Monday\n' #Back to results >>> f.readlines() #call the readlines() function ['Tuesday\n', 'Wednesday\n', 'Thursday\n', 'Friday\n', 'Saturday\n', 'Sunday\n'] #Back to results