[英]How to insert into middle of line in file in Python
我在文件“code.s”中有以下代码:
movi $1,10
beginning: jeq $1, $0,done
addi $1, $1,-1
j beginning
done: halt
我想在文件中的每个“:”字符之后直接插入一个换行符 '\\n'。 我将如何在 Python 中执行此操作?
根据文件的大小,您可以尝试将其作为字符串读入内存。
然后使用yourstring.replace(target, replacement)
函数,将每个":"
替换为":\\n"
。
将此数据写回您的文件:
with open("code.s", "w") as the_file:
# This will delete the contents of the file, make a backup
the_file.write(yourstring)
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.