Python 如何替换文本文件中的一行?

Python 如何替换文本文件中的一行?,python,Python,如何用python替换文本文件中的特定行 TXT文件(stock.TXT): ID名称 0341螺钉 0345钉子 代码: 我尝试过几种方法,包括fileinput,但似乎都不管用 import fileinput file = open("stock.txt") search = "0341" for a in file: if search in a: searched_line = a for line in fileinput.input(file, inp

如何用python替换文本文件中的特定行

TXT文件(stock.TXT):

ID名称
0341螺钉
0345钉子
代码:

我尝试过几种方法,包括
fileinput
,但似乎都不管用

import fileinput

file = open("stock.txt")
search = "0341"
for a in file:
    if search in a:
        searched_line = a

for line in fileinput.input(file, inplace = True):
    line.replace(searched_line, string_to_replace)
返回了一个错误:

OSError:[WinError 123]文件名、目录名或卷标语法不正确


我可能遗漏了一些重要的东西,但是其他人有什么想法吗?

错误只是因为它找不到目录/文件,你一定是路径/到/文件错误,但我认为你的代码不是最好的,你应该这样做来替换一行:

string_to_replace = "HEYA"
with open('tests.txt', 'r') as f:
    text = f.read()
    text = text.replace(string_to_replace, 'REPLACE BY MEE PLEASEEEE')

with open('tests.txt', 'w') as f:
    f.write(text)

我不完全确定您为什么会得到
OSError
,但下面的代码没有遇到它,并且似乎做了您想要做的事情(在Windows 7上测试):


几个问题:(1)第一个参数必须是一个文件名,而不是一个打开的文件,(2)
inplace=True
只意味着输出最终会替换原始文件,但您仍然需要写出所有内容,(3)
line.replace()
操作不到位,您必须捕获返回值感谢您的回答。我不知道
Python
中有一个名为
fileinput
@nexus66的内置模块:不客气。使用它有点棘手,因为当使用
inplace=True
时,它将
stdout
重定向到输入文件。虽然我怀疑这不是乌托邦;如今,它已经实现了这么多功能,除了这里所示的功能之外,它还可以做其他一些有用的事情,并使编写Unix(如从
stdin
读取)和写入
stdout
类型的实用程序变得更容易。查看链接。我将查看链接。谢谢。
string_to_replace = "HEYA"
with open('tests.txt', 'r') as f:
    text = f.read()
    text = text.replace(string_to_replace, 'REPLACE BY MEE PLEASEEEE')

with open('tests.txt', 'w') as f:
    f.write(text)
import fileinput

search = "0341"
string_to_replace = "0341    Rivets"

for line in fileinput.input("stock.txt", inplace=True):
    line = line.rstrip()
    if search in line:
        line = string_to_replace
    print(line)