如何使用 python 中的行号输入查找和替换文件中的字符串
How to find and replace string in a file using input of line number in python
我的要求是从一个目录中找到一个文件,然后在该文件中找到 LOG_X_PARAMS 并在第一个逗号后附加一个字符串,这就是我现在所拥有的
import os, fnmatch
def findReplacelist(directory, finds, new_string, file):
line_number = 0
list_of_results = []
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
with open(filepath, 'r') as f:
for line in f:
line_number += 1
if finds in line:
list_of_results.append((line_number))
print(list_of_results)
def get_git_root(path):
Path = "E:\Code\modules"
file_list=["pb_sa_ch.c"]
for i in file_list:
findReplacelist(Path , "LOG_1_PARAMS", "instance", i)
示例行如下更改
LOG_X_PARAMS(string 1, string 2); #string1 andd string2 is random
这个到
LOG_X_PARAMS(string 1, new_string, string 2);
我可以使用 LOG_X_PARAMS 找到行号,现在使用此行号 我需要在同一行中附加一个字符串 有人可以帮忙解决吗?
这就是我完成任务的方式。我会找到我想要更改的文件,然后逐行读取文件,如果文件中有更改,则将文件写回。方法如下:
def findReplacelist(directory, finds, new_string, file):
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
find_replace(finds, new_string, filepath)
def find_replace(tgt_phrase, new_string, file):
outfile = ''
chgflg = False
with open(file, 'r') as f:
for line in f:
if tgt_phrase in line:
outfile += line + new_string
chgflg = True
else:
outfile += line
if chgflg:
with open(file, 'w') as f:
f.write(outfile)
我的要求是从一个目录中找到一个文件,然后在该文件中找到 LOG_X_PARAMS 并在第一个逗号后附加一个字符串,这就是我现在所拥有的
import os, fnmatch
def findReplacelist(directory, finds, new_string, file):
line_number = 0
list_of_results = []
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
with open(filepath, 'r') as f:
for line in f:
line_number += 1
if finds in line:
list_of_results.append((line_number))
print(list_of_results)
def get_git_root(path):
Path = "E:\Code\modules"
file_list=["pb_sa_ch.c"]
for i in file_list:
findReplacelist(Path , "LOG_1_PARAMS", "instance", i)
示例行如下更改
LOG_X_PARAMS(string 1, string 2); #string1 andd string2 is random
这个到
LOG_X_PARAMS(string 1, new_string, string 2);
我可以使用 LOG_X_PARAMS 找到行号,现在使用此行号 我需要在同一行中附加一个字符串 有人可以帮忙解决吗?
这就是我完成任务的方式。我会找到我想要更改的文件,然后逐行读取文件,如果文件中有更改,则将文件写回。方法如下:
def findReplacelist(directory, finds, new_string, file):
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
find_replace(finds, new_string, filepath)
def find_replace(tgt_phrase, new_string, file):
outfile = ''
chgflg = False
with open(file, 'r') as f:
for line in f:
if tgt_phrase in line:
outfile += line + new_string
chgflg = True
else:
outfile += line
if chgflg:
with open(file, 'w') as f:
f.write(outfile)