Python 在文件中查找字符串并替换整行
我最近刚刚接触python,正在尝试编写一个脚本。 搜索文件中的字符串并替换整行的最简单方法是什么。我已经发现re.sub可以实现这一点,但没有任何东西足够具体,我可以做到这一点 例如:Python 在文件中查找字符串并替换整行,python,linux,scripting,Python,Linux,Scripting,我最近刚刚接触python,正在尝试编写一个脚本。 搜索文件中的字符串并替换整行的最简单方法是什么。我已经发现re.sub可以实现这一点,但没有任何东西足够具体,我可以做到这一点 例如: #configuration file Stuff that configures a file 到 通过搜索配置 这个命令还有不同的功能,比如搜索字符串吗 在中间的一行,并替换它之后的所有内容。< p>可以使用替换来替换端口号。 with open('resume.txt', 'r') as
#configuration file
Stuff that configures a file
到
通过搜索配置
这个命令还有不同的功能,比如搜索字符串吗
在中间的一行,并替换它之后的所有内容。< p>可以使用替换来替换端口号。
with open('resume.txt', 'r') as file:
file_data = file.read()
upd_port = file_data.replace('22', '4832')
with open('resume.txt', 'w') as file:
file.write(upd_port)
请告诉我们您的尝试:此外,这可能会帮助您开始
with open('resume.txt', 'r') as file:
file_data = file.read()
upd_port = file_data.replace('22', '4832')
with open('resume.txt', 'w') as file:
file.write(upd_port)