一个简单的文件操作练习

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个简单的文件操作练习相关的知识,希望对你有一定的参考价值。

首先你需要在当前目录下穿件一个Blowing in the wind.txt文件,内容自定

我们我们需要在行首插入两句话,并且在行尾插入一句话,内容随意

实现代码如下:

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 #打开已有文件,以读写模式打开
 5 with open(Blowing in the wind.txt,r+) as f:
 6     lst_r = f.readlines()
 7 
 8 #分别插入
 9 lst_r.insert(0,Blowin \‘in the wind\r\n\r\n)    
10 lst_r.insert(1,Bob Dylan)
11 lst_r.insert(len(lst_r),\r\n\r\n1962 by Warner Bros. Inc.)
12 
13 #写入新文件
14 with open(Blowing in the wind_2.txt,w+) as f2:
15     for i in lst_r:
16         f2.write(i)
17         

 

以上是关于一个简单的文件操作练习的主要内容,如果未能解决你的问题,请参考以下文章