从零学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中几种导入模块的方式总结
Apr 27 Python
Python时间的精准正则匹配方法分析
Aug 17 Python
Python实现解析Bit Torrent种子文件内容的方法
Aug 29 Python
PyQt5每天必学之像素图控件QPixmap
Apr 19 Python
python使用paramiko模块通过ssh2协议对交换机进行配置的方法
Jul 25 Python
Python的Lambda函数用法详解
Sep 03 Python
Python文件路径名的操作方法
Oct 30 Python
Python解压 rar、zip、tar文件的方法
Nov 19 Python
Windows下python3安装tkinter的问题及解决方法
Jan 06 Python
Python3查找列表中重复元素的个数的3种方法详解
Feb 13 Python
python中Ansible模块的Playbook的具体使用
May 28 Python
pandas apply使用多列计算生成新的列实现示例
Feb 24 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的日期处理函数及uchome的function_coomon中日期处理函数的研究
2011/01/12 PHP
PHP字符串的编码问题的详细介绍
2013/04/27 PHP
解析PHP中的unset究竟会不会释放内存
2013/07/18 PHP
PHP加密解密类实例分析
2015/04/20 PHP
php处理复杂xml数据示例
2016/07/11 PHP
PHP实现将标点符号正则替换为空格的方法
2017/08/09 PHP
javascript实现的动态文字变换
2007/07/28 Javascript
JavaScript类和继承 prototype属性
2010/09/03 Javascript
Javascript基础教程之关键字和保留字汇总
2015/01/18 Javascript
AngularJS数据源的多种获取方式汇总
2016/02/02 Javascript
使用原生js写ajax实例(推荐)
2017/05/31 Javascript
微信小程序图片选择区域裁剪实现方法
2017/12/02 Javascript
如何用vue-cli3脚手架搭建一个基于ts的基础脚手架的方法
2019/12/12 Javascript
Python实现完整的事务操作示例
2017/06/20 Python
django 发送邮件和缓存的实现代码
2018/07/18 Python
Python subprocess库的使用详解
2018/10/26 Python
在pycharm中设置显示行数的方法
2019/01/16 Python
Python中numpy模块常见用法demo实例小结
2019/03/16 Python
使用python将mysql数据库的数据转换为json数据的方法
2019/07/01 Python
基于PyQT实现区分左键双击和单击
2020/05/19 Python
OpenCV+Python3.5 简易手势识别的实现
2020/12/21 Python
django inspectdb 操作已有数据库数据的使用步骤
2021/02/07 Python
德国传统玻璃制造商:Cristalica
2018/04/23 全球购物
Annoushka英国官网:英国奢侈珠宝品牌
2018/10/20 全球购物
面向对象概念面试题(.NET)
2016/11/04 面试题
前台领班岗位职责
2013/12/04 职场文书
列车长先进事迹材料
2014/01/25 职场文书
党员干部公开承诺书
2014/03/26 职场文书
法律顾问服务方案
2014/05/15 职场文书
小学生关于梦想的演讲稿
2014/08/22 职场文书
机械专业毕业生自我鉴定2014
2014/10/04 职场文书
学雷锋日活动总结
2015/02/06 职场文书
2015年八一建军节慰问信
2015/03/23 职场文书
Mysql中一千万条数据怎么快速查询
2021/12/06 MySQL
Elasticsearch 索引操作和增删改查
2022/04/19 Python
详解apache编译安装httpd-2.4.54及三种风格的init程序特点和区别
2022/07/15 Servers