第一次写的shell原文件修改方法:
#!/bin/bash
read -p "please insert file name > " file_name //file_name=文件路径+文件名
old_str='搜索的字符串'
new_str='需要修改的字符串'
sed -i "s/$old_str*/$new_str/g" $file_name
在原文件内写入,python3方法:
def ex_file(file):
file_data=""
old_str = '要修改的字符串'
with open(file,"r",encoding="utf-8") as f:
for line in f: #逐行读取文件内容
if old_str in line: #判断字符串是否存在行
line =line.replace(old_str,old_str+"要修改的字符串")
#格式为line = line.replace(老字符串,新字符串)
file_data += line
with open(file,"w",encoding="utf-8") as f: #在原文件里面写入
f.write(file_data)
if __name__ == '__main__':
file = input("请输入文件路径:\n")+ "\\test.txt"
ex_file(file)