如何在Python中插入到文件行的中间

2024-09-29 17:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在“code.s”文件中有以下代码:

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

我想在文件中的每个“:”字符后直接插入换行符“\n”。我将如何在Python中执行此操作


Tags: 文件代码code字符donebeginningmovihalt
2条回答

根据文件的大小,您可以尝试将其作为字符串读入内存

然后使用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()

相关问题 更多 >

    热门问题