Python has basic text file reading and writing capabilities. Python's standard library provides richer read and write functions.
The reading and writing of text files is mainly realized through the file object constructed by open().
Create file object
We open a file and use an object to represent the file:
f = open(filename, mode)
The most common patterns are:
"r" # read only
"w" # write
for example
>>>f = open("test.txt","r")
methods of the file object
Read:
content = f.read(N) # Read N bytes of data
content = f.readline() # read a line
content = f.readlines() # Read all lines, store in a list, each element is a line.
write:
f.write('I like apple') # Write 'I like apple' to the file
Close the file:
f.close()
practise
Create a record.txt document with the following content:
tom, 12, 86Lee, 15, 99 Lucy, 11, 58Joseph, 19, 56
Then read the file from record.txt and print it.
Summarize
f = open(name, "r")
line = f.readline()
f.write('abc')
f.close()