Python has basic text file reading and writing capabilities, and Python's standard library provides richer read and write capabilities.
Text files are read and written primarily through the file object built by open () to achieve
To create a file object
We open a file and apply an object to represent the file:
f = open (file name, mode)
The most commonly used patterns are:
"R" # read-only
"W" # Write
Like what
>>>f = open ("Test.txt", "R")
Methods for File objects
Read:
Content = F.read (n) # reads N bytes of data
Content = F.readline () # reads a line
Content = F.readlines () # reads all rows, is stored in the list, and each element is a row.
Write:
F.write (' I like Apple ') # write ' I like Apple ' to file
To close a file:
F.close ()
Practice
Create a Record.txt document and write the following:
Tom, 12, 86
Lee, 15, 99
Then read the file from the Record.txt and print it.
Summarize
f = open (name, "R")
line = F.readline ()
F.write (' abc ')
F.close ()
Python Advanced 02 text file input and output