This question has already been answered:

There is a text file with a separation like this:

1|2|3|4|5|6 

How can I insert additional text between a certain number and | ?

For example, I need to insert the text after the number 3 :

 1|2|3/чтонибудь|4|5|6 

Reported as a duplicate by participants aleksandr barakin , Alexey Shimansky , Denis Bubnov , Sasha Omelchenko , jfs python 5 May '17 at 1:17 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    You can split a string, you can replace. Democracy - MihailPw
  • one
    The file will have to be overwritten completely, the text is not a DB table. So: read everything, correct, write everything down. - Akina
  • it is also possible with rewriting, but according to the idea you can simply save the result in a separate file, say - Sergey Shcherbakov
  • Yes, everything written to another file is not prohibited. - Akina

1 answer 1

 with open('in.txt', 'rt') as in_f: with open('out.txt', 'wt') as out_f: for line in in_f: # out.write(line.replace('|3|', '|3|что нибудь|') lst = line.split('|') out_f.write('|'.join(lst[:3] + ['что нибудь'] + lst[3:])) 
  • The fact is that 3 is always different (there is a different text) - Sergey Shcherbakov
  • ie, you need to determine the position on the separator and indicate that we add exactly to the end / something | before the separator is closed - Sergey Shcherbakov
  • @SergeyShcherbakov make the question clearer. Then so. - andy.37
  • hmm, it looks all right, I could not find the parts: lst = line.split ('|') and out.write ('|' .join (lst [: 3] + ['something') + lst [3 :])) - Sergey Shcherbakov
  • but now writes: File "run.py", line 1 with open ('in.txt', 'rt') as in: ^ SyntaxError: invalid character in identifier - Sergey Shcherbakov