Skip to content

Commit a752268

Browse files
committed
Program that Replaces Specified Text String In a Text File
1 parent 8c67c8c commit a752268

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

text_file_replace.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
Author: Linjian Li (github.com/LinjianLi)
3+
Created: 2020-04-09
4+
Last Modified: 2020-04-09
5+
6+
Description: A script that replace specified text string in a text file.
7+
8+
How to use: `-f` specifying the text file,
9+
`-e` specifying the encoding (optional),
10+
`-o` specifying the old text string to be replaced),
11+
`-n` specifying the new text string to replace with.
12+
"""
13+
14+
import argparse
15+
16+
parser = argparse.ArgumentParser()
17+
parser.add_argument("-f", "--file", help = "File.")
18+
parser.add_argument("-e", "--encoding", default='utf-8', help = "Encoding.")
19+
parser.add_argument("-o", "--old", help = "Old string.")
20+
parser.add_argument("-n", "--new", help = "New string.")
21+
args = parser.parse_args()
22+
23+
f = args.file
24+
e = args.encoding
25+
o = args.old
26+
n = args.new
27+
28+
lines = []
29+
with open(file=f, mode='r', encoding=e) as fd:
30+
for line in fd:
31+
lines.append(line.replace(o, n))
32+
33+
with open(file=f, mode='w', encoding=e) as fd:
34+
fd.writelines(lines)

0 commit comments

Comments
 (0)