从零学python系列之从文件读取和保存数据


Posted in Python onMay 23, 2014

在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例:

 

新建IDLE会话,首先导入os模块,并将工作目录却换到包含文件“sketch.txt”的文件夹,如C:\\Python33\\HeadFirstPython\\chapter3

>>> import os
>>> os.getcwd()    #查看当前工作目录
'C:\\Python33'
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3')   #切换包含数据文件的文件夹
>>> os.getcwd()     #查看切换后的工作目录
'C:\\Python33\\HeadFirstPython\\chapter3'

打开文件“sketch.txt”,读取并显示前两行:

>>> data=open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.

回到文件起始位置,使用for语句处理文件中的每行,最后关闭文件:

>>> data.seek(0)   #使用seek()方法回到文件起始位置
>>> for each_line in data:
    print(each_line,end='')
    
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()

读取文件后,将不同role对应数据分别保存到列表man和other:

import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
man=[]    #定义列表man接收Man的内容
other=[]  #定义列表other接收Other Man的内容
try:
    data=open("sketch.txt")
    for each_line in data:
        try:
            (role, line_spoken)=each_line.split(':', 1)
            line_spoken=line_spoken.strip()
            if role=='Man':
                man.append(line_spoken)
            elif role=='Other Man':
                other.append(line_spoken)
        except ValueError:
                pass
    data.close()
except IOError:
    print('The datafile is missing!')
print (man)
print (other)

Tips:

使用open()方法打开磁盘文件时,默认的访问模式为r,表示读,不需要特意指定;

要打开一个文件完成写,需要指定模式w,如data=open("sketch.txt","w"),如果该文件已经存在则会清空现有内容;

要追加到一个文件,需要指定模式a,不会清空现有内容;

要打开一个文件完成写和读,且不清空现有内容,需要指定模式w+;

 例如,将上例中保存的man和other内容以文件方式保存时,可修改如下:

import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
man=[]
other=[]
try:
    data=open("sketch.txt")
    for each_line in data:
        try:
            (role, line_spoken)=each_line.split(':', 1)
            line_spoken=line_spoken.strip()
            if role=='Man':
                man.append(line_spoken)
            elif role=='Other Man':
                other.append(line_spoken)
        except ValueError:
                pass
    data.close()
except IOError:
    print('The datafile is missing!')
try:
    man_file=open('man.txt', 'w')      #以w模式访问文件man.txt
    other_file=open('other.txt','w')   #以w模式访问文件other.txt
    print (man, file=man_file)           #将列表man的内容写到文件中
    print (other, file=other_file)
except IOError:
    print ('File error')
finally:
    man_file.close()
    other_file.close()

但是第26行print()为什么会报错?“syntax error while detecting tuple”,有大神能给解惑一下不

Python 相关文章推荐
python避免死锁方法实例分析
Jun 04 Python
举例讲解Python中的迭代器、生成器与列表解析用法
Mar 20 Python
Python安装使用命令行交互模块pexpect的基础教程
May 12 Python
浅谈python 线程池threadpool之实现
Nov 17 Python
Django框架搭建的简易图书信息网站案例
May 25 Python
Django高级编程之自定义Field实现多语言
Jul 02 Python
利用Python实现Shp格式向GeoJSON的转换方法
Jul 09 Python
Django实现发送邮件功能
Jul 18 Python
python如何编写win程序
Jun 08 Python
Python socket服务常用操作代码实例
Jun 22 Python
pycharm使用技巧之自动调整代码格式总结
Nov 04 Python
python脚本使用阿里云slb对恶意攻击进行封堵的实现
Feb 04 Python
从零学python系列之浅谈pickle模块封装和拆封数据对象的方法
May 23 #Python
从零学python系列之新版本导入httplib模块报ImportError解决方案
May 23 #Python
从零学python系列之数据处理编程实例(二)
May 22 #Python
从零学python系列之数据处理编程实例(一)
May 22 #Python
Python学习笔记_数据排序方法
May 22 #Python
从零学Python之hello world
May 21 #Python
Python开发实例分享bt种子爬虫程序和种子解析
May 21 #Python
You might like
关于PHP中操作MySQL数据库的一些要注意的问题
2006/10/09 PHP
调试一段PHP程序时遇到的三个问题
2012/01/17 PHP
php 获取本地IP代码
2013/06/23 PHP
thinkPHP基于ajax实现的菜单与分页示例
2016/07/12 PHP
php 命名空间(namespace)原理与用法实例小结
2019/11/13 PHP
Yii 框架使用Forms操作详解
2020/05/18 PHP
文本框中,回车键触发事件的js代码[多浏览器兼容]
2010/06/07 Javascript
HTML长文本截取含有HTML代码同样适用的两种方法
2013/07/31 Javascript
JavaScript列表框listbox全选和反选的实现方法
2015/03/18 Javascript
JS选中checkbox后获取table内一行TD所有数据的方法
2015/07/01 Javascript
js实现的万能flv网页播放器代码
2016/04/30 Javascript
使用JS实现图片展示瀑布流效果(简单实例)
2016/09/06 Javascript
Vue-router 切换组件页面时进入进出动画方法
2018/09/01 Javascript
node中IO以及定时器优先级详解
2019/05/10 Javascript
Vue CLI3中使用compass normalize的方法
2019/05/30 Javascript
[03:00]2014DOTA2国际邀请赛 Titan淘汰潸然泪下Ohaiyo专访
2014/07/15 DOTA
Python使用urllib模块的urlopen超时问题解决方法
2014/11/08 Python
为Python的web框架编写MVC配置来使其运行的教程
2015/04/30 Python
django开发之settings.py中变量的全局引用详解
2017/03/29 Python
在Qt5和PyQt5中设置支持高分辨率屏幕自适应的方法
2019/06/18 Python
python制作朋友圈九宫格图片
2019/11/03 Python
python的json中方法及jsonpath模块用法分析
2019/12/06 Python
20行Python代码实现一款永久免费PDF编辑工具的实现
2020/08/27 Python
利用Canvas模仿百度贴吧客户端loading小球的方法示例
2017/08/13 HTML / CSS
Mankind西班牙男士护肤品网站:购买皮肤护理、护发和剃须
2017/04/27 全球购物
Zadig&Voltaire官网:法国时装品牌
2018/01/05 全球购物
MSC邮轮官方网站:加勒比海、地中海和世界各地的假期
2018/08/27 全球购物
工作自荐信
2013/12/11 职场文书
经典安踏广告词
2014/03/21 职场文书
学习实践科学发展观心得体会
2014/09/10 职场文书
出纳试用期自我鉴定范文
2014/09/16 职场文书
单位未婚证明范本
2014/11/25 职场文书
2015年求职自荐信范文
2015/03/04 职场文书
纪委立案决定书
2015/06/24 职场文书
解决numpy和torch数据类型转化的问题
2021/05/23 Python
漫改真人电影「萌系男友是燃燃的橘色」公开先导视觉图
2022/03/21 日漫