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() #最后,关闭文件
运行结果:
(完)
网址: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() #最后,关闭文件
运行结果:
(完)
相关文章推荐
- python 参数传递[打包与解包问题]
- DayDayUP_Python自学教程[12]_Python正则表达式
- python numpy
- python的一些函数
- Python/Pelican搭建自己个人博客
- ipyhon 与 ipython notebook
- Python为什么不隐式实现self
- Python核心编程 第八章练习
- python生成随机数方法小结
- Python字符串操作汇总
- python爬虫抓取51cto博客大牛的文章保存到本地excel文件
- python logging 日志轮转文件不删除问题
- Python对list列表结构中的值进行去重的方法总结
- python 学习笔记 8(闭包)
- Python环境下安装使用异步任务队列包Celery的基础教程
- urllib&urllib2库--python2.X(学习日记1)
- Mac下安装opencv-python
- python 文件读写5个实例
- Python2 连接MySQL
- Python关键字yield的解释(stackoverflow)