RealFL RealFL - 1 year ago 83
Python Question

Change nth occurence of a character with another character in every line of text file

I have a text file, Text.txt where each line looks like this:

1, 2, 3, 4, name.docx, , 5, 6, 7

Where the numbers change from one line to the next, but not name.docx (and yes, that space between name and 5 was intentional).
I'm looking to change the fifth comma (that is, the one after the "name.docx") to another character, i.e. "@" - but I need to do this for every line. How might this be done?

Note: I know that something like this, for some string, can be used to change the nth occurence of a certain character in a line to another (in this case a comma with "@"):

re.sub(r'^((.*?,.*?){n}),', r'\[email protected]', mystring)

However I don't know the most efficient way to apply this to all lines.

Answer Source
with open('your_text_file.txt') as file_obj:
    for line in file_obj.readlines():
        values = line.strip().split(',')
        values[4] += '@' + values[5]
        del values[5]
        print ','.join(values)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download