Home > Mobile >  How to insert into middle of line in file in Python
How to insert into middle of line in file in Python

Time:10-19

I have the following code in a file "code.s":

   movi $1,10
beginning: jeq $1, $0,done
   addi $1, $1,-1
   j beginning
done: halt

I want to insert a newline character '\n' directly after each ":" character in the file. How would I go about doing this in Python?

CodePudding user response:

Depending on the size of your file, you can try reading it into memory as a string.

Then using the yourstring.replace(target, replacement) function, replace each ":" with ":\n".

Write this data back to your file:

with open("code.s", "w") as the_file:
    # This will delete the contents of the file, make a backup
    the_file.write(yourstring)

CodePudding user response:

import os
os.chdir(r'C:\Users\LAVANYA\OneDrive\Documents\am3') 
file=open('am2.txt','r')
doc=file.readlines()
a=[]
for i in doc:
    a.append(i.replace(":",":\n"))
file=open('am2.txt','w')
file.writelines(a)
file.close()
  • Related