Article From:https://www.cnblogs.com/URNOTBENBEN/p/9215454.html

【Circulate the file

fw = open(‘nhy’,’w’)

for line in fw:  

  print(‘line:’,line)   #Direct loop file object, each cycle is to take the data of each row.

fw.flush()    #Write the data in the buffer to disk immediately.

with open(‘nhy’,’w’) as fw, open(‘nhy2′,’w’) as fw2 :       #Using with, you can automatically close the file, and when the file is finished (using with to open multiple files).
  fw.read()
  fw.write(‘xxx’)

 

【File modification]

**Idea one: simple and direct and direct

1、Get all the contents in the file first
2、Then modify the content
3、Emptying the contents of the original document
4、Rewrite

eg:Replace 123 in the file as Python
 f = open(‘users.txt’,’a+’)
 f.seek(0)
 all_data = f.read()
 new_data = all_data.replace(‘123′,’python’)
 f.seek(0)
 f.truncate()    #Emptying the contents of the file
 f.write(new_data)
 f.flush()
 f.close()

**Idea two: efficient way of handling

1、First open the original file, then open an empty file.
2、Process every row of data in the original file and write it to the new file after processing.
3、Delete the original file and change the name of the new file to the name of the original file.

 

eg:Modify the document to meet the following requirements:

1、The front space
2、Get rid of the empty line
3、You replace you
4、Write to the new document
5、Delete the original file and change the name of the new file to the name of the original file.
      import os
      with open(‘words’,encoding=’utf-8′) as fr, open(‘.words’,’w’,encoding=’utf-8′) as fw:
   for line in fr:
    line = line.lstrip() #Remove the left space
    if line:#Determine whether the line has data
    line = line.replace(‘You ‘,’you’) replace the data
    fw.write(line)#Write to the new document

  os.remove(‘words’)#Delete the original file
  os.rename(‘.words’,’words’) #Change the name of the new file to the name of the original file

Link of this Article: Python base (three) file operation

Leave a Reply

Your email address will not be published. Required fields are marked *