从零学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实现进程间通信简单实例
Jul 23 Python
使用PDB模式调试Python程序介绍
Apr 05 Python
python生成tensorflow输入输出的图像格式的方法
Feb 12 Python
pytorch: tensor类型的构建与相互转换实例
Jul 26 Python
python自动化生成IOS的图标
Nov 13 Python
解决Python一行输出不显示的问题
Dec 03 Python
Python3爬虫教程之利用Python实现发送天气预报邮件
Dec 16 Python
PyQt5 对图片进行缩放的实例
Jun 18 Python
Django框架 查询Extra功能实现解析
Sep 04 Python
python安装virtualenv虚拟环境步骤图文详解
Sep 18 Python
Python中无限循环需要什么条件
May 27 Python
如何在向量化NumPy数组上进行移动窗口
May 18 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
叶罗丽:为什么大家对颜冰这对CP非常关心,却对金茉两人十分冷漠
2020/03/17 国漫
dedecms 制作模板中使用的全局标记图文教程
2007/03/11 PHP
深入探讨:PHP使用数据库永久连接方式操作MySQL的是与非
2013/06/05 PHP
解决laravel5中auth用户登录其他页面获取不到登录信息的问题
2019/10/08 PHP
不错的JS中变量相关的细节分析
2007/08/13 Javascript
变量声明时命名与变量作为对象属性时命名的区别解析
2013/12/06 Javascript
完善的jquery处理机制
2016/02/21 Javascript
使用vue.js开发时一些注意事项
2016/04/27 Javascript
jQuery旋转插件jqueryrotate用法详解
2016/10/13 Javascript
用v-html解决Vue.js渲染中html标签不被解析的问题
2016/12/14 Javascript
js仿淘宝商品放大预览功能
2017/03/15 Javascript
实例讲解Vue.js中router传参
2018/04/22 Javascript
解决vue中post方式提交数据后台无法接收的问题
2018/08/11 Javascript
JQuery获取可视区尺寸和文档尺寸及制作悬浮菜单示例
2019/05/14 jQuery
nuxt踩坑之Vuex状态树的模块方式使用详解
2019/09/06 Javascript
vue实现网络图片瀑布流 + 下拉刷新 + 上拉加载更多(步骤详解)
2020/01/14 Javascript
vue radio单选框,获取当前项(每一项)的value值操作
2020/09/10 Javascript
解决nuxt 自定义全局方法,全局属性,全局变量的问题
2020/11/05 Javascript
js前端传json后台接收‘‘被转为quot的问题解决
2020/11/12 Javascript
[50:27]OG vs LGD 2018国际邀请赛淘汰赛BO3 第一场 8.26
2018/08/30 DOTA
python实现数通设备端口监控示例
2014/04/02 Python
浅析Python中的多进程与多线程的使用
2015/04/07 Python
把csv文件转化为数组及数组的切片方法
2018/07/04 Python
python调用百度地图WEB服务API获取地点对应坐标值
2019/01/16 Python
pip指定python位置安装软件包的方法
2019/07/12 Python
Python参数传递实现过程及原理详解
2020/05/14 Python
div或img图片高度随宽度自适应的方法
2020/02/06 HTML / CSS
Paul Smith英国官网:英国国宝级时装品牌
2019/03/21 全球购物
什么是Rollback Segment
2013/04/22 面试题
特色蛋糕店创业计划书
2014/01/28 职场文书
2014年党的群众路线整改措施思想汇报
2014/10/12 职场文书
欠条样本
2015/07/03 职场文书
欢送领导祝酒词
2015/08/12 职场文书
2016年党课培训学习心得体会
2016/01/07 职场文书
微前端qiankun改造日渐庞大的项目教程
2022/06/21 Javascript
Win11 Beta 22621.601 和 22622.601今日发布 KB5017384修复内容汇总
2022/09/23 数码科技