I am trying to modify a variable in a C source file using python, but it only appends the line to the end of the file. What am I doing wrong and is there an easier way to do this? Below is a snippet of my source code.
with open(file, 'r ') as f:
filedata = f.readlines()
for l in filedata:
if 'char key[]' in l: # look for a char array called key
l = l.split('=') # split the variable into a list
l[1] = l[1].replace(l[1], key) # Replace the first element with a value of my own
print(l[1]) # see what the new value is
f.writelines(l[1]) # attempt to modify just the first element, which is the contents of the variable, but this appends to the end of the C file
CodePudding user response:
When you read a file, you move the pointer in it (fh.tell()
) and must .seek()
to it again if you need the same position
If you're changing the lines, you need to rewrite everything afterwards and should .truncate()
for safety or you can have muddled contents from partially-clobbered later lines or trailing partial data at the end (if you write less than the file originally contained)
Note that the later positions change when re-writing earlier content, so it's usually best to get all your lines and rewrite the entire file at once rather than repeatedly re-writing it (if possible) .. if you have a very large file, which is less-likely with source files, but still possible, breaking it up into chunks may be required / help
CodePudding user response:
You can't modify a file in-place like you are trying to do. One solution here is to write the output to a new file. Then you can delete the old file and rename the new one to the same name as the old one. Note that you will have to write every line that you don't change to the new file as well as the line that you change.