0

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'\1@', mystring)

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

RealFL
  • 117
  • 4
  • 11
  • 1
    if you already know how to do it for one string, the just extend it to line by line no? `for line in lines: re.sub...` – Vince W. Jul 26 '17 at 19:50

2 Answers2

1
file_lines = []
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]
        file_lines.append(','.join(values))

with open('your_text_file.txt', 'w') as f:
    f.write('\n'.join(file_lines))
Harrichael
  • 395
  • 3
  • 11
  • Yeah, all I'm looking to do is replace the comma after the "docx" with "@" for every line – RealFL Jul 26 '17 at 19:55
  • It looks like this is deleting all characters between the fifth and sixth commas - I want to keep those (all I need is to replace the fifth comma, alone, with "@") – RealFL Jul 26 '17 at 20:03
  • Edited post with changes – Harrichael Jul 26 '17 at 20:09
  • In the future, you should break down your problem into parts. Think of a step by step process to get what you want, then ask a pointed question for what you don't know how to code. For your open ended problem here, its hard to tell if you didn't know how to 1) open files, 2) write files, 3) read lines, or 4) manipulate strings – Harrichael Jul 26 '17 at 20:14
  • Duly noted - I'm also having trouble getting this to actually change the "your_text_file.txt". If I use something like a = (','.join(values)) and then f=open("your_text_file.txt", "w") followed by f.write(a), I see no changes in my text file. I supose this has to do with the nature of a in this case - do you know how I could get this to directly modify the text file itself? – RealFL Jul 26 '17 at 20:55
  • 1
    I edited, but there is already a good answer for that out there:https://stackoverflow.com/a/6160082/4480742 – Harrichael Jul 26 '17 at 21:01
1

Another solution:

def change_nth_occurrence(x, n, a, b):
    """
    Change the n'th occurence of 'a' in x to 'b'.
    """
    indices = [i for i, c in enumerate(x) if c == a]
    pos = indices[n - 1] # n is 1-based
    return x[:pos] + b + x[pos+1:]

Usage:

change_nth_occurrence('aaaaa', 2, 'a', 'b')
change_nth_occurrence('1, 2, 3, 4, name.docx, , 5, 6, 7', 5, ',', '@')
# works with lists, but note that 'b' must be given as a list
change_nth_occurrence([1, 1, 1, 1, 1], 3, 1, [2])

Results:

'abaaa'
'1, 2, 3, 4, name.docx@ , 5, 6, 7'
[1, 1, 2, 1, 1]