我的.txt文件如下
Pyhton is open source language
its a freeware
it has lot of in built modules
python is easiest如何在its freeware行下面插入两行,并将剩余的数据移到插入行的下面,如下所示:
Pyhton is open source language
its a freeware
Hi
my name is shubham
it has lot of in bult modules
python is easiest我尝试了下面的代码,但最后还是在文件中添加了新的行
file_to_write = r"file.txt"
with open(file_to_write,'a') as fw:
fw.write('Hi\n')
fw.write('my name is shubham')发布于 2018-02-26 19:01:13
为了创建一个新行,在字符串中想要添加新行的位置之前添加\n。
\n =移动到下一行,因此如果需要进一步向下移动,只需添加更多的\n,例如:
\n\n =向下移动2行。
举例说明。
text = "Python is an open source language. \nits a freeware \n\nHi my name is shubham. it has lot of in built modules python is easiest"
with open("test.txt", "w") as f:
f.write(text)注意我是如何将所有的文本都包含在一个变量中的,并且每当我需要插入一行(或者几行)的时候,我都会在文本前加上一个或多个\n。
现在,所有信息都存储在单个变量text中,我现在可以简单地将text变量作为参数传递给写函数,并将其适当地保存在test.txt文件中。
https://stackoverflow.com/questions/48986740
复制相似问题