-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.py
More file actions
20 lines (18 loc) · 997 Bytes
/
replace.py
File metadata and controls
20 lines (18 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os, argparse
def main(args):
for file in os.listdir(args.dir):
if file.endswith(".txt"):
with open(os.path.join(args.dir, file), "r", encoding="utf-8") as f:
lines = f.readlines()
with open(os.path.join(args.dir, file), "w", encoding="utf-8") as f:
for line in lines:
if args.replace in line:
line = line.replace(args.replace, args.replacement)
f.write(line)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Replace a string in all .txt files in the current directory.")
parser.add_argument("--replace", type=str, required=True, help="String to replace")
parser.add_argument("--replacement", type=str, required=True, help="Replacement string")
parser.add_argument("--dir", type=str, default="./", help="Directory to search for .txt files, defaults to current directory")
args = parser.parse_args()
main(args)