mimisico100 mimisico100 - 10 days ago 5
Python Question

How do you replace a line in a text file?

How would I replace a specific line in a text file with python?

TXT FILE (stock.txt):

ID NAME
0341 Screws
0345 Nails


Code:

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


I have tried several methods including
fileinput
, but none of them seem to work.

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)


That returned an error:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect


I am probably missing something big, but does anyone else have any ideas?

Answer

The error is just because it can't find the directory/file, you must have the path/to/file wrong, but i think your code it's not the greatest as it is, you should do it like this to replace a line:

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)