Example 1:
CopyCodeThe Code is as follows :#! /Usr/bin/Python
Import sys
Import re
If _ name __= = "_ main __":
F = file ("hi.txt", "W + ")
Li = ["Hello \ n", "Hi \ n"]
F. writelines (Li)
F. Close ()
"W +" Mode: If there is no hi.txt, a file is created and written to the directory. If there is no hi.txt file, the hi.txt content is cleared and written to the directory again.
Example 2: Modify the specified row of a file
The method is relatively stupid. The file content is read into a list by row, and the specified row is modified to assign values to the elements in the list. After modification, the list is written to a new file using writelines.
Copy codeThe Code is as follows :#! /Usr/bin/Python
Import sys, OS
F=open('hi.txt ', 'r + ')
Flist = f. readlines ()
Flist [4] = 'Hi \ N'
F=open('hi.txt ', 'W + ')
F. writelines (flist)
Modify the content of the fifth line of hi.txt to hi