L0g*_*g1x 2 python io insert tokenize writetofile
我有一个我正在阅读的文件
fo = open("file.txt", "r")
Run Code Online (Sandbox Code Playgroud)
然后通过做
file = open("newfile.txt", "w")
file.write(fo.read())
file.write("Hello at the end of the file")
fo.close()
file.close()
Run Code Online (Sandbox Code Playgroud)
我基本上将文件复制到新文件,但也在新创建的文件末尾添加一些文本.我怎么能插入那条线,在由空行分隔的两条线之间?即:
line 1 is right here
<---- I want to insert here
line 3 is right here
Run Code Online (Sandbox Code Playgroud)
我可以通过分隔符\n来标记不同的句子吗?
首先,您应该使用该open()方法加载文件,然后应用.readlines()拆分"\n"并返回列表的方法,然后通过在列表之间插入新字符串来更新字符串列表,然后简单地将列表的内容写入使用的新文件new_file.write("\n".join(updated_list))
注意:此方法仅适用于可以加载到内存中的文件.
with open("filename.txt", "r") as prev_file, open("new_filename.txt", "w") as new_file:
prev_contents = prev_file.readlines()
#Now prev_contents is a list of strings and you may add the new line to this list at any position
prev_contents.insert(4, "\n This is a new line \n ")
new_file.write("\n".join(prev_contents))
Run Code Online (Sandbox Code Playgroud)