0

Similar to posting: Replace string in a specific line using python, however results were not forethcomming in my slightly different instance.

I working with python 3 on windows 7. I am attempting to batch edit some files in a directory. They are basically text files with .LIC tag. I'm not sure if that is relevant to my issue here. I am able to read the file into python without issue. My aim is to replace a specific string on a specific line in this file.

import os
import re

groupname = 'Oldtext'
aliasname = 'Newtext'

with open('filename') as f:
    data = f.readlines()
    data[1] = re.sub(groupname,aliasname, data[1])
    f.writelines(data[1])

print(data[1])
print('done')

When running the above code I get an UnsupportedOperation: not writable. I am having some issue writing the changes back to the file. Based on suggestion of other posts, I edited added the w option to the open('filename', "w") function. This causes all text in the file to be deleted.

Based on suggestion, the r+ option was tried. This leads to successful editing of the file, however, instead of editing the correct line, the edited line is appended to the end of the file, leaving the original intact.

2
  • try using the mode r+, which opens the file for both reading and writing Commented Apr 26, 2017 at 16:46
  • I tried your suggestion. This enables me to edit the file, however the modified line is simply appended to the file instead of editing the desired line. Commented Apr 26, 2017 at 17:00

1 Answer 1

0

Writing a changed line into the middle of a text file is not going to work unless it's exactly the same length as the original - which is the case in your example, but you've got some obvious placeholder text there so I have no idea if the same is true of your actual application code. Here's an approach that doesn't make any such assumption:

with open('filename', 'r') as f:
    data = f.readlines()
data[1] = re.sub(groupname,aliasname, data[1])
with open('filename', 'w') as f:
    f.writelines(data)

EDIT: If you really wanted to write only the single line back into the file, you'd need to use f.tell() BEFORE reading the line, to remember its position within the file, and then f.seek() to go back to that position before writing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.