Simple file manipulation python modifies the method in which the file specifies the line

  • 2020-04-02 13:10:43
  • OfStack

      Example 1:


#!/usr/bin/python
import sys
import re
if __name__=="__main__":
 f=file("hi.txt","w+")
 li=["hellon","hin"]
 f.writelines(li)
 f.close()

      "W+" mode: if there is no hi. TXT to create a file to write; If it exists, clear the contents of hi.txt and rewrite.

  Example 2: modify the line specified in the file

      The method used is stupid, the file contents are read into a list by line, modify the specified line that is to assign values to the elements in the list; When you are done, write the list back to the file using writelines.

     


#!/usr/bin/python
import sys,os
f=open('hi.txt','r+')
flist=f.readlines()
flist[4]='hin'
f=open('hi.txt','w+')
f.writelines(flist)

      Change the contents of line 5 of hi. TXT to hi


Related articles: