您的位置:首页 > 编程语言 > Python开发

python 文件读写项目实践

2016-05-07 20:55 411 查看
在博客(Python本地数据获取
  网址:http://blog.csdn.net/sxingming/article/details/51333663)中,我们详细介绍了python中文件读写的各种方法。本文我们示例一个文件读写的小项目:

项目要求如下:



python2代码如下

f=open(r'C:\Users\Administrator\Desktop\Blowing in the wind.txt','w+') #创建文件,准备写入数据。注意打开模式是'w+',因为我们不仅要写数据,最后还要读数据。

l=['How many roads must a man walk down\n',

'Before they call him a man\n',

'How many seas must a white dove sail\n',

'Before she sleeps in the sand\n',

'How many times must the cannon balls fly\n',

"Before they're forever banned\n",

'The answer my friend is blowing in the wind\n',

'The answer is blowing in the wind']

f.writelines(l) #将歌词写入文件

f.seek(0)#将文件指针移到文件开头。准备读数据

lines=f.readlines()#读取歌词

lines.insert(0,"Blowin' in the wind     Bob Dylan\n")#在文件头部插入歌名和歌手信息

lines.append("\n1962 by Warner Bros.Inc.\n") #在文件尾部插入一行信息

f.seek(0,0)#将文件指针移到文件开头。准备写数据

f.writelines(lines) #将插入信息后的列表写入文件中

f.seek(0)#将文件指针移到文件开头

for line in f:#文件对象时可迭代的

    print line[:-1] #通过切片的方式,将每一行最后的换行符去掉。

f.close() #最后,关闭文件

运行结果:



(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: