python 文件读写项目实践

在博客(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() #最后,关闭文件

运行结果:


(完)


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值