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

时间:2016-11-26 23:01:15

标签: python

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

TXT FILE(stock.txt):

ID      NAME
0341    Screws
0345    Nails

代码:

file = open("stock.txt")
string_to_replace = "0341    Rivets"

我尝试过多种方法,包括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] The filename, directory name, or volume label syntax is incorrect

我可能错过了一些大事,但其他人有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我不完全确定您为什么要获得OSError,但这里的代码没有遇到它并且似乎做了您想要的(测试时) Windows 7):

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)

答案 1 :(得分:0)

错误只是因为它无法找到目录/文件,你必须有路径/ to / file错误,但我认为你的代码并不是最好的,你应该这样做可以替换一行:

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)