Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在文件中查找字符串并替换整行_Python_Linux_Scripting - Fatal编程技术网

Python 在文件中查找字符串并替换整行

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

我最近刚刚接触python,正在尝试编写一个脚本。 搜索文件中的字符串并替换整行的最简单方法是什么。我已经发现re.sub可以实现这一点,但没有任何东西足够具体,我可以做到这一点

例如:

    #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)