From a752268938d4273cfa506b8c538648b13e70093f Mon Sep 17 00:00:00 2001 From: LinjianLi Date: Thu, 9 Apr 2020 10:51:19 +0800 Subject: [PATCH] Program that Replaces Specified Text String In a Text File --- text_file_replace.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 text_file_replace.py diff --git a/text_file_replace.py b/text_file_replace.py new file mode 100644 index 00000000000..9ab2befed08 --- /dev/null +++ b/text_file_replace.py @@ -0,0 +1,34 @@ +""" +Author: Linjian Li (github.com/LinjianLi) +Created: 2020-04-09 +Last Modified: 2020-04-09 + +Description: A script that replace specified text string in a text file. + +How to use: `-f` specifying the text file, + `-e` specifying the encoding (optional), + `-o` specifying the old text string to be replaced), + `-n` specifying the new text string to replace with. +""" + +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument("-f", "--file", help = "File.") +parser.add_argument("-e", "--encoding", default='utf-8', help = "Encoding.") +parser.add_argument("-o", "--old", help = "Old string.") +parser.add_argument("-n", "--new", help = "New string.") +args = parser.parse_args() + +f = args.file +e = args.encoding +o = args.old +n = args.new + +lines = [] +with open(file=f, mode='r', encoding=e) as fd: + for line in fd: + lines.append(line.replace(o, n)) + +with open(file=f, mode='w', encoding=e) as fd: + fd.writelines(lines) \ No newline at end of file