lundi 2 mars 2015

How to insert a specific string into a specific location of a specific line in a file using a Python script?

There's this line in 'file.txt' that says:



memcpy(buffer, "", 64)


I want to write a Python script that reads this file.txt and locates this line in it. Then, it proceeds to insert a specific string (stored in a variable 'data') between the two quotes ("") in that line.


For example, if the variable data contains the value 'foo bar', then the line would be modified by the Python script to:



memcpy(buffer, "foo bar", 64)


Here's what I have tried:



for line in fileinput.input('file.txt', inplace=1):
if line.startswith('memcpy(buffer, \"'):
print data


It didn't work because it wiped out the entire file.txt and when I opened it it was blank.


Aucun commentaire:

Enregistrer un commentaire