从零学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返回真假值(True or False)小技巧
Apr 10 Python
python中dir函数用法分析
Apr 17 Python
Java中重定向输出流实现用文件记录程序日志
Jun 12 Python
编写Python脚本抓取网络小说来制作自己的阅读器
Aug 20 Python
Python给你的头像加上圣诞帽
Jan 04 Python
Python闭包执行时值的传递方式实例分析
Jun 04 Python
python实现图片批量压缩程序
Jul 23 Python
python中pip的使用和修改下载源的方法
Jul 08 Python
python 函数嵌套及多函数共同运行知识点讲解
Mar 03 Python
Django models filter筛选条件详解
Mar 16 Python
Python使用tkinter制作在线翻译软件
Feb 22 Python
4种方法python批量修改替换列表中元素
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制作静态网站的模板框架
2006/10/09 PHP
用PHP实现的随机广告显示代码
2007/06/14 PHP
PHP加速 eAccelerator配置和使用指南
2009/06/05 PHP
php stripslashes和addslashes的区别
2014/02/03 PHP
PHP给源代码加密的几种方法汇总(推荐)
2018/02/06 PHP
JQuery中的$.getJSON 使用说明
2011/03/10 Javascript
JS onmousemove鼠标移动坐标接龙DIV效果实例
2013/12/16 Javascript
Javascript改变CSS样式(局部和全局)
2013/12/18 Javascript
javascript实现随时变化着的背景颜色
2015/04/02 Javascript
Javascript 基础---Ajax入门必看
2016/07/06 Javascript
Angularjs实现mvvm式的选项卡示例代码
2016/09/08 Javascript
JS时间控制实现动态效果的实例讲解
2017/07/31 Javascript
jQuery实现对网页节点的增删改查功能示例
2017/09/18 jQuery
JS实现的将html转为pdf功能【基于浏览器端插件jsPDF】
2018/02/06 Javascript
jQuery实现每隔一段时间自动更换样式的方法分析
2018/05/03 jQuery
element-ui 文件上传修改文件名的方法示例
2019/11/05 Javascript
Vue表单提交点击事件只允许点击一次的实例
2020/10/23 Javascript
react+antd 递归实现树状目录操作
2020/11/02 Javascript
python 输出上个月的月末日期实例
2018/04/11 Python
对Python中for复合语句的使用示例讲解
2018/11/01 Python
详解python环境安装selenium和手动下载安装selenium的方法
2020/03/17 Python
详解pyinstaller生成exe的闪退问题解决方案
2020/06/19 Python
使用Nibabel库对nii格式图像的读写操作
2020/07/01 Python
DJI美国:消费类无人机领域的领导者
2018/04/27 全球购物
Linux不知道文件后缀名怎么判断文件类型
2012/04/26 面试题
会计学应届毕业生推荐信
2013/11/04 职场文书
网页设计个人找工作求职信
2013/11/28 职场文书
六十岁生日答谢词
2014/01/10 职场文书
记帐员岗位责任制
2014/02/08 职场文书
禁止酒驾标语
2014/06/25 职场文书
2015年试用期工作总结
2014/12/12 职场文书
2015年度质量工作总结报告
2015/04/27 职场文书
2015年主婚人婚礼致辞
2015/07/28 职场文书
热爱劳动主题班会
2015/08/14 职场文书
2016新年问候语大全
2015/11/11 职场文书
缓存替换策略及应用(以Redis、InnoDB为例)
2021/07/25 Redis