从零学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中zip()函数用法实例教程
Jul 31 Python
Python统计列表中的重复项出现的次数的方法
Aug 18 Python
Python通过PIL获取图片主要颜色并和颜色库进行对比的方法
Mar 19 Python
详解Python如何获取列表(List)的中位数
Aug 12 Python
win7+Python3.5下scrapy的安装方法
Jul 31 Python
python 对字典按照value进行排序的方法
May 09 Python
python双端队列原理、实现与使用方法分析
Nov 27 Python
使用Matplotlib 绘制精美的数学图形例子
Dec 13 Python
python global和nonlocal用法解析
Feb 03 Python
python文件操作seek()偏移量,读取指正到指定位置操作
Jul 05 Python
python中return不返回值的问题解析
Jul 22 Python
Python opencv缺陷检测的实现及问题解决
Apr 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
咖啡店都有些什么常规豆子呢?有什么风味在里面
2021/03/04 咖啡文化
简单PHP上传图片、删除图片实现代码
2010/05/12 PHP
PHP 函数学习简单小结
2010/07/08 PHP
php学习之 数组声明
2011/06/09 PHP
PHP中提问频率最高的11个面试题和答案
2014/09/02 PHP
菜鸟javascript基础整理1
2010/12/06 Javascript
jquery实现手机发送验证码的倒计时代码
2014/02/12 Javascript
JavaScript中数组继承的简单示例
2015/07/29 Javascript
jQuery实现鼠标滑过链接控制图片的滑动展开与隐藏效果
2015/10/28 Javascript
将JavaScript的jQuery库中表单转化为JSON对象的方法
2015/11/17 Javascript
JS读写CSS样式的方法汇总
2016/08/16 Javascript
前端框架Vue.js中Directive知识详解
2016/09/12 Javascript
jQuery页面弹出框实现文件上传
2017/02/09 Javascript
vue.js 上传图片实例代码
2017/06/22 Javascript
vue系列之requireJs中引入vue-router的方法
2018/07/18 Javascript
解决vue-quill-editor上传内容由于图片是base64的导致字符太长的问题
2018/08/20 Javascript
layui动态渲染生成select的option值方法
2019/09/23 Javascript
Vue.js的模板语法详解
2020/02/16 Javascript
maptalks+three.js+vue webpack实现二维地图上贴三维模型操作
2020/08/10 Javascript
JS实现炫酷轮播图
2020/11/15 Javascript
Python决策树分类算法学习
2017/12/22 Python
Python实现按逗号分隔列表的方法
2018/10/23 Python
Python对象转换为json的方法步骤
2019/04/25 Python
Python传递参数的多种方式(小结)
2019/09/18 Python
使用CSS3的背景渐变Text Gradient 创建文字颜色渐变
2014/08/19 HTML / CSS
印度婴儿用品在线商店:Firstcry.com
2016/12/05 全球购物
教育合作协议范本
2014/10/17 职场文书
2014年党建工作汇报材料
2014/11/02 职场文书
2014年依法行政工作总结
2014/11/19 职场文书
幼儿园推普周活动总结
2015/05/07 职场文书
小学生反邪教心得体会
2016/01/15 职场文书
《蟋蟀的住宅》教学反思
2016/02/17 职场文书
SQL Server 数据库实验课第五周——常用查询条件
2021/04/05 SQL Server
MySQL 5.7常见数据类型
2021/07/15 MySQL
tomcat下部署jenkins的方法
2022/05/06 Servers
nginx sticky实现基于cookie负载均衡示例详解
2022/12/24 Servers