Substituting a string in a designated line of an unconventional text file

The revised edition of qdata includes a function that is designed to handle lines of different lengths. It scans through all the lines until it locates the desired one, and then only modifies that specific line without making any changes to the others. As a result, the process should be relatively fast. This function is responsible for removing any lines that solely consist of the DEL character and saving the updated content to a new file.


Unless the changed line has the same length as the original, it is not possible to write it into the middle of a text file. In your example, the changed line has the same length, but since there is placeholder text, it is unclear if this holds true for your actual application code. To address this, here’s an alternative approach that doesn’t rely on this assumption.

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

EDIT: To write only the single line back into the file, you would first use


to record its position within the file, and then use

to return to that position before writing.

Frequently Asked Questions