从零学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 随机数生成的代码的详细分析
May 15 Python
Python使用pyodbc访问数据库操作方法详解
Jul 05 Python
pandas中apply和transform方法的性能比较及区别介绍
Oct 30 Python
python实现flappy bird游戏
Dec 24 Python
基于OpenCV python3实现证件照换背景的方法
Mar 22 Python
树莓派动作捕捉抓拍存储图像脚本
Jun 22 Python
python字符串Intern机制详解
Jul 01 Python
Pandas0.25来了千万别错过这10大好用的新功能
Aug 07 Python
关于Python turtle库使用时坐标的确定方法
Mar 19 Python
Python如何脚本过滤文件中的注释
May 27 Python
python 多线程爬取壁纸网站的示例
Feb 20 Python
python数据可视化JupyterLab实用扩展程序Mito
Nov 20 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中全局变量global和$GLOBALS[]的区别分析
2012/08/06 PHP
php获取QQ头像并显示的方法
2014/12/23 PHP
php上传图片获取路径及给表单字段赋值的方法
2016/01/23 PHP
Javascript技术技巧大全(五)
2007/01/22 Javascript
jquery下异步提交表单 异步跨域提交表单
2010/11/17 Javascript
js中通过父级进行查找定位元素
2014/06/15 Javascript
js实现照片墙功能实例
2015/02/05 Javascript
JavaScript学习小结(7)之JS RegExp
2015/11/29 Javascript
javascript实现移动端上的触屏拖拽功能
2016/03/04 Javascript
JavaScript 字符串常用操作小结(非常实用)
2016/11/30 Javascript
Node.js复制文件的方法示例
2016/12/29 Javascript
vue.js中指令Directives详解
2017/03/20 Javascript
基于JavaScript实现带数据验证和复选框的表单提交
2017/08/23 Javascript
详解webpack提取第三方库的正确姿势
2017/12/22 Javascript
解决layui上传文件提示上传异常,实际文件已经上传成功的问题
2018/08/19 Javascript
vue 实现购物车总价计算
2019/11/06 Javascript
layui实现显示数据表格、搜索和修改功能示例
2020/06/03 Javascript
NodeJS开发人员常见五个错误理解
2020/10/14 NodeJs
Python实现去除代码前行号的方法
2015/03/10 Python
在Python中使用sort()方法进行排序的简单教程
2015/05/21 Python
Python中的字符串查找操作方法总结
2016/06/27 Python
Python 日期区间处理 (本周本月上周上月...)
2019/08/08 Python
pytorch 实现在预训练模型的 input上增减通道
2020/01/06 Python
通过python连接Linux命令行代码实例
2020/02/18 Python
python画环形图的方法
2020/03/25 Python
Django QuerySet查询集原理及代码实例
2020/06/13 Python
CSS3盒子模型详解
2013/04/24 HTML / CSS
英国最大的化装舞会服装网站:Fancydress.com
2017/08/15 全球购物
意大利在线高尔夫商店:Online Golf
2021/03/09 全球购物
工作自我评价分享
2013/12/01 职场文书
自我评价怎么写正确呢?
2013/12/02 职场文书
校园门卫岗位职责
2013/12/09 职场文书
多媒体编辑专业毕业生求职信
2014/06/13 职场文书
详细聊聊关于Mysql联合查询的那些事儿
2021/10/24 MySQL
Python OpenCV之常用滤波器使用详解
2022/04/07 Python
Python 装饰器(decorator)常用的创建方式及解析
2022/04/24 Python