Two ways to modify the file

1  # first way modify the file: 
2  "" " 
3  modify the file:
 4  1. Memory read data from a hard disk (file read)
 5  2. Complete modification (replacement string) in the memory
 6  3. then covered the original content (write file)
 . 7  replace replaced
 . 8  "" " 
. 9  
10 with Open (R & lt ' Test02 ' , ' R & lt ' , encoding = ' UTF-. 8 ' ) AS F:
 . 11      RES = reached, f.read ()
 12 is      Print ( RES)
 13 is with Open (R & lt ' Test02 ' , ' W ' ,encoding=' UTF-. 8 ' ) AS F:
 14      Data = res.replace ( ' Jeff ' , ' GYY ' )    # replaced 
15      Print (Data)
 16      f.write (Data)
 . 17  "" " 
18 is  advantages: only one file on the hard disk
 19  disadvantages: when the file is too large, it may cause memory overflow
 20  "" " 
21  
22
# 23 The second way to modify the file: 
24-Import os
25 "" "
26 1. Create a new file
27 2. Read the old contents of the file into memory modification will write the new contents of the edited file among
28 3. old the name of the file to delete old files into new files
29 "" "
30 with Open (r'test02 ',' r ', encoding =' UTF-8 ') AS read_f, \
31 Open (r'test02.swap', 'A', encoding = 'UTF-. 8') AS write_f:
32 for Line in read_f:
33 is NEW_LINE = line.replace ( 'GYY', 'CJM')
34 is write_f.write (NEW_LINE)
35 The os.remove (R & lt ' test02 ') # delete the old file
36 os.rename (r'test02.swap', 'test02 ') # new file renamed the old file name
37 "" "
38 Pros: memory is always only a single line, not the memory
39 shortcomings : There are two files simultaneously on the hard disk at a time
40 "" "
41

 

Guess you like

Origin www.cnblogs.com/guyouyin123/p/11160299.html