从零学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牛刀小试密码爆破
Feb 03 Python
Python写的Tkinter程序屏幕居中方法
Mar 10 Python
深入理解Python分布式爬虫原理
Nov 23 Python
Python中列表与元组的乘法操作示例
Feb 10 Python
详解Python中where()函数的用法
Mar 27 Python
Python神奇的内置函数locals的实例讲解
Feb 22 Python
Python中遍历列表的方法总结
Jun 27 Python
Flask使用Pyecharts在单个页面展示多个图表的方法
Aug 05 Python
Python Scrapy框架第一个入门程序示例
Feb 05 Python
python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例
Mar 10 Python
Python实现抖音热搜定时爬取功能
Mar 16 Python
基于Python实现对比Exce的工具
Apr 07 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 insert语法详解
2008/06/07 PHP
PHP 文件类型判断代码
2009/03/13 PHP
创建数据库php代码 用PHP写出自己的BLOG系统
2010/04/12 PHP
关于Iframe如何跨域访问Cookie和Session的解决方法
2013/04/15 PHP
ThinkPHP模板引擎之导入资源文件方法详解
2014/06/18 PHP
Yii2使用小技巧之通过 Composer 添加 FontAwesome 字体资源
2014/06/22 PHP
php文件压缩之PHPZip类用法实例
2015/06/18 PHP
php监测数据是否成功插入到Mysql数据库的方法
2016/11/25 PHP
laravel实现分页样式替换示例代码(增加首、尾页)
2017/09/22 PHP
Tab页界面 用jQuery及Ajax技术实现(php后台)
2011/10/12 Javascript
js获取网页高度(详细整理)
2012/12/28 Javascript
JS的document.all函数使用示例
2013/12/30 Javascript
js利用数组length属性清空和截短数组的小例子
2014/01/15 Javascript
js 采用delete实现继承示例代码
2014/05/20 Javascript
js跨浏览器的事件侦听器和事件对象的使用方法
2015/12/17 Javascript
JS上传组件FileUpload自定义模板的使用方法
2016/05/10 Javascript
浅谈js基本数据类型和typeof
2016/08/09 Javascript
jQuery插件ajaxFileUpload异步上传文件
2016/10/19 Javascript
jquery ajaxfileupload异步上传插件使用详解
2017/02/08 Javascript
Three.JS实现三维场景
2018/12/30 Javascript
如何使用CSS3+JQuery实现悬浮墙式菜单
2019/06/18 jQuery
vue中提示$index is not defined错误的解决方式
2020/09/02 Javascript
python根据出生年份简单计算生肖的方法
2015/03/27 Python
python 全局变量的import机制介绍
2017/09/07 Python
Python反射用法实例简析
2017/12/22 Python
python实现剪切功能
2019/01/23 Python
利用Python库Scapy解析pcap文件的方法
2019/07/23 Python
北美女性服装零售连锁店:maurices
2019/06/12 全球购物
New delete 与malloc free 的联系与区别
2013/02/04 面试题
采购主管的岗位职责
2013/12/17 职场文书
优质服务活动实施方案
2014/05/02 职场文书
县级领导干部开展党的群众路线教育实践活动工作汇报
2014/10/25 职场文书
单方离婚协议书范本2014
2014/10/28 职场文书
先进党员事迹材料
2014/12/24 职场文书
2019年国庆祝福语(70句)
2019/09/19 职场文书
mysql5.6主从搭建以及不同步问题详解
2021/12/04 MySQL