Reading and writing text files for advanced python tutorials

  • 2020-04-02 14:03:14
  • OfStack

Python has basic text file reading and writing capabilities. Python's standard library provides richer read-write capabilities.

Text files are read and written primarily through the file object built by open().

Create file object

We open a file and use an object to represent the file:


f = open( File name, mode )

 
The most common patterns are:

"r"     # read-only
" w "      # write

Such as


>>>f = open("test.txt","r")

Method of the file object

Read:


content = f.read(N)          # read N bytes The data of content = f.readline()       # Read a line content = f.readlines()      # All rows are read, stored in a list, and each element is a row.

Writing:


f.write('I like apple')      # will 'I like apple' Written to the file

 
Close file:

f.close()

practice

Create a record. TXT document, write as follows:

Tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
Then from record. TXT to read the file and print.

conclusion


f    = open(name, "r")
line = f.readline()
f.write('abc')
f.close()


Related articles: