Reading and writing text files in the python advanced tutorial,
Python has the basic function of reading and writing text files. 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:
Copy codeThe Code is as follows:
F = open (file name, Mode)
The most common modes are:
Copy codeThe Code is as follows:
"R" # Read-Only
"W" # Write
For example
Copy codeThe Code is as follows:
>>> F = open ("test.txt", "r ")
File object Method
Read:
Copy codeThe 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:
Copy codeThe Code is as follows:
F. write ('I like apple') # write' I like apple' to a file
Close the file:
Copy codeThe 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
Copy codeThe Code is as follows:
F = open (name, "r ")
Line = f. readline ()
F. write ('abc ')
F. close ()