python global replacement program

Keywords: PHP encoding Python Windows

Exercise 1 - global replacement procedure:

1. Write a script to allow the user to perform global replacement of the specified file content as follows
  python your_script.py old_str new_str filename
2. After the replacement, print how many parts have been replaced

1. Contents of TXT:

Ma Xianyu Shenzhen 173 13744234523
Qiao Yifei Guangzhou 173 15823423525
Luomengzhu Beijing 173 18523424221
Liu nuohan Beijing 173 1852342765
Yuenini Shenzhen 173 18835324553
He wanxuan Shenzhen 173 18533434452
Ye Zixuan Shanghai 173 18042432324

Code:

 1 # @Time     :2019/6/8 20:57
 2 # -*- encoding:utf-8 -*-
 3 
 4 import os
 5 import sys
 6 
 7 my_sys = sys.argv  # Receive input parameters
 8 if len(my_sys) != 4:
 9     print("Wrong inputing!")
10     os._exit(0)
11 else:
12     print("Replacing....")
13 old_str = str(my_sys[1])
14 new_str = str(my_sys[2])
15 filename = my_sys[3]
16 new_file = filename + "_new"
17 
18 count = 0  # count
19 with open(filename, mode='r', encoding='utf-8') as f:
20     data = f.read()
21     if old_str in data:
22         data = data.split("\n")  # use\n Split string output to list
23 
24         f_new = open(new_file, mode='w', encoding='utf-8')
25 
26         for i in data:  # i = 'Ma Xian Yu     Shenzhen    173 13744234523'
27             if old_str in i:
28                 count += 1
29             i = i.replace(old_str, new_str)
30             f_new.write(i + "\n")  # write file
31         f_new.close()
32 
33 if count > 0:
34     if os.path.exists(filename):
35         os.remove(filename)
36     os.replace(new_file, filename)
37     # os.rename("contacts_new", "contacts") #Windows has no rename function
38     print("Replace successfully,Replaced{0}place".format(count))
39 else:
40     print("{0}Not in file{1}".format(filename, old_str))

Execute script:

Ideas for modifying the contents of documents:

Open the original file in read mode, open a new file in write mode, read the contents of the original file into memory for modification, and then write the new file.

Finally, using the method of os module, delete the original file and rename the new file to the original file name (see lines 34, 35, 36).

Posted by axnoran on Fri, 01 Nov 2019 02:55:12 -0700