This article mainly introduces the reading and writing of text files in the python advanced tutorial. This article describes the most basic file reading and writing functions, for more information about how to read and write text files, see Python. The Python Standard Library provides richer read/write functions.
The read and write operations on text files are mainly implemented by file objects built by open.
Create a file object
Open a file and use an object to represent the file:
The code is as follows:
F = open (file name, mode)
The most common modes are:
The code is as follows:
"R" # read-only
"W" # write
For example
The code is as follows:
>>> F = open ("test.txt", "r ")
File object method
Read:
The code is as follows:
Content = f. read (N) # read data of N bytes
Content = f. readline () # read a row
Content = f. readlines () # read all rows and store them in the list. each element is a row.
Write:
The code is as follows:
F. write ('I like apple') # write' I like Apple' to a file
Close the file:
The code is as follows:
F. close ()
Exercise
Create a record.txt file. the written content is as follows:
Tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
Then read and print the file from record.txt.
Summary
The code is as follows:
F = open (name, "r ")
Line = f. readline ()
F. write ('ABC ')
F. close ()