Search code examples
pythonpython-3.xio

Replace string at index in multiple files


I have a hundred files in a directory. They look like

abc def
ghi 123456
xyz

I want to change 123456 to XXXXXX I cannot use a regex because the string is not always the same but it's always at the same index and has always the same length

What I tried in python 3.7

#!/usr/bin/python
import fileinput
import glob

for filepath in glob.iglob('mydir/*.txt'):
    with fileinput.FileInput(filepath, inplace=True) as file:
        for index, line in enumerate(file):
            if index == 1:
                print(line.replace(line[9:14], "XXXXXX"))

1- This replaces the whole file with the modified text

2- 123456 is replaced by XXXXXX6 (9:14 being the real boundaries in my files)

How can I fix this script?


Solution

  • To do the replacing, simply write:

    print(line[:9] + "XXXXXX" + line[14:])
    

    Don't bother with str.replace; it could lead to unexpected behaviour in this case.

    The reason that the original code was leaving the 6 was because slices don't include the final index.


    To print the whole file, use the following code:

    for index, line in enumerate(file):
        if index == 1:
            line = line[:9] + "XXXXXX" + line[14:]
        print(line, end="")
    

    The end="" is because iterating over lines in a file keeps the \n character at the end of each line, so we need to tell print not to add its own or we get a blank line in between each line of the file.