[英]Find and replace texts in all files from the text file input using Python in Notepad++
[英]Find and replace certain texts in file using python
我有以下文本文件:
1- VERSION_CONTROL {
2- FILE_NAME = "foo.cmp";
3- REVISION = "";
4- AUTHOR = "doo";
5- DATE = "Date: ";
6- }
7-
8- CVTS {
9- CVTLIST = {
10- {
11- CVT = "foo";
12- }
13- }
14- }
15- IFREAL {
16- LOADLIST = "";
17- UNLOADLIST = "";
18- IOMAPLIST = {
19- }
20- }
21- IFSIM {
22- SIMULATIONS = {
23- SIMULATION {
24- NAME = "";
25- PROGRAM = "foo.zip";
26-
27- RATE = "1";
28- OFFSET = "0";
29- SUBFRAME = "0";
30- LENGTH = "1";
31- ARGUMENTS = "";
32- OPTIONS = "RT";
33- LOOPS = "1";
34- cpumask = "0";
35- }
36- }
37- LOADLIST = "";
38- UNLOADLIST = "";
39- }
40-
我正在尝试替换变量LOADLIST = "";
与LOADLIST = "init";
但是,仅在第 37 行。到目前为止,我的解决方案:
reading_file = open(myFile.txt,"r")
new_file_content = ""
for line in reading_file:
stripped_line = line.strip()
new_line = stripped_line.replace('LOADLIST = "";', 'LOADLIST = "initScwss";')
new_file_content += new_line +"\n"
reading_file.close()
writing_file = open(entry, "w")
writing_file.write(new_file_content)
writing_file.close()
我的代码的问题在于它会在它找到的任何地方填充LOADLIST
,这意味着在第 16,17,37 16,17, 37 & 38
行。
知道如何过滤搜索以便只考虑第37
行吗? 提前致谢
假设您无法将 txt 文件更改为 json,如果您只想更改 IFSIM 之后的 LOADLIST,则可以使用 state-fullness 来检查循环是否已到达 IFSIM。
entry = "outfile.txt"
reading_file = open("myFile.txt","r")
new_file_content = ""
isIfsim = False
for line in reading_file:
stripped_line = line.strip()
if "IFSIM" in stripped_line:
isIfsim = True
if isIfsim:
if 'LOADLIST = "";' in stripped_line:
new_line = stripped_line.replace('LOADLIST = "";', 'LOADLIST = "init";')
new_file_content += new_line +"\n"
isIfsim = False
else:
new_file_content += stripped_line +"\n"
else:
new_file_content += stripped_line +"\n"
reading_file.close()
writing_file = open(entry, "w")
writing_file.write(new_file_content)
writing_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.