Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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 - Fatal编程技术网

Python 用字符串替换文件行

Python 用字符串替换文件行,python,Python,我有一个.txt文件,我想在其中用字符串替换一个特定的行(第3行)。我不想使用简单的file.replace(targetString,newString),因为我在文件中有多个targetString,它们的顺序未知。我知道我要替换的字符串总是在第三行,这是第三行上唯一的东西 目前我的代码看起来像这样,我在编程方面很糟糕,所以我希望你能想到最简单的答案 with open("LAB5INFO.txt", "r+") as file: content = file.read()

我有一个.txt文件,我想在其中用字符串替换一个特定的行(第3行)。我不想使用简单的file.replace(targetString,newString),因为我在文件中有多个targetString,它们的顺序未知。我知道我要替换的字符串总是在第三行,这是第三行上唯一的东西

目前我的代码看起来像这样,我在编程方面很糟糕,所以我希望你能想到最简单的答案

with open("LAB5INFO.txt", "r+") as file:
    content = file.read()
    file.seek(0)
    file.truncate()
    file.write(content.replace(<<LINE3>>, string))
打开(“LAB5INFO.txt”,“r+”)作为文件:
content=file.read()
file.seek(0)
file.truncate()文件
file.write(content.replace(,string))
我想是吧

with open("LAB5INFO.txt", "rb") as file:
    lines = file.readlines()
    lines[2].replace("old","new")
with open("LAB5INFO.txt", "wb") as file:
    file.write("\n".join(lines)

借用其他答案,但这里我们不需要知道原始行的内容

with open("LAB5INFO.txt", "rb") as file:lines = file.readlines()
lines[2]="new third line"
with open("LAB5INFO.txt", "wb") as file: file.write("\n".join(lines))

嗨,奥利弗,我对你的问题做了一些修改。我从标题中去掉了Python标记;因为不鼓励使用标签。更重要的是,我更改了代码块的间距。因为这是python,所以间距的变化非常显著。如果您发现我所做的更改不是您所编写代码的真实表示,请编辑问题或回滚我的更改。此外,如果您在编程方面很糟糕,为什么不在编辑器中打开文件并更改该行?(如果您想在批处理脚本中更改该行,通常会有一些脚本替代方案可以满足您的需要。)