Modify file operations

Today to share with you the basic process of modifying files in python:

Changed file operation process: 1, the original file is opened in read mode.

         2. Create a new file in write mode.

         3, the original contents of the file is modified to read out the new content written to the new file.

         4, the original file is deleted.

         5, rename the new file to the original file.

Import os
 # 1, open the original file in read mode. 
# 2, create a new file in write mode. 
Open with ( ' round in circles ' , encoding = ' UTF-. 8 ' ) AS F1, \ 
    Open ( ' round in circles .bak ' , encoding = ' UTF-. 8 ' , MODE = ' W ' ) AS F2:
 # . 3, the the contents of the original file is modified to read out the new content, new file is written. 
    for Line in f1:
         # first cycle SB old boy python sponsor, founder. 
        = line.replace NEW_LINE ( ' SB ' , ' Alex ' )
        f2.write (NEW_LINE) 
The os.remove ( ' round in circles ' ) 
os.rename ( ' round in circles .bak ' , ' going round in circles ' )

 

Guess you like

Origin www.cnblogs.com/cui-xuefei/p/10992893.html
Recommended