从零学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中还原JavaScript的escape函数编码后字符串的方法
Aug 22 Python
python执行外部程序的常用方法小结
Mar 21 Python
八大排序算法的Python实现
Jan 28 Python
Python 使用SMTP发送邮件的代码小结
Sep 21 Python
python K近邻算法的kd树实现
Sep 06 Python
python实现五子棋小游戏
Mar 25 Python
python使用phoenixdb操作hbase的方法示例
Feb 28 Python
Python实现带下标索引的遍历操作示例
May 30 Python
python实现电子书翻页小程序
Jul 23 Python
TensorFlow2.1.0安装过程中setuptools、wrapt等相关错误指南
Apr 08 Python
浅谈多卡服务器下隐藏部分 GPU 和 TensorFlow 的显存使用设置
Jun 30 Python
用python写PDF转换器的实现
Oct 29 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
ThinkPHP中处理表单中的注意事项
2014/11/22 PHP
php实现cookie加密的方法
2015/03/10 PHP
Javascript注入技巧
2007/06/22 Javascript
jQuery代码优化 选择符篇
2011/11/01 Javascript
js写一个字符串转成驼峰的实例
2013/06/21 Javascript
jQuery实现统计复选框选中数量
2014/11/24 Javascript
javascript定义变量时带var与不带var的区别分析
2015/01/12 Javascript
nodejs简单实现中英文翻译
2015/05/04 NodeJs
jQuery中clone()函数实现表单中增加和减少输入项
2017/05/13 jQuery
微信小程序实现自定义picker选择器弹窗内容
2020/05/26 Javascript
在vue中v-bind使用三目运算符绑定class的实例
2018/09/29 Javascript
JavaScript实现简单轮播图效果
2018/12/01 Javascript
vue中多个倒计时实现代码实例
2019/03/27 Javascript
mongodb初始化并使用node.js实现mongodb操作封装方法
2019/04/02 Javascript
vue实现Input输入框模糊查询方法
2021/01/29 Javascript
理解Python中的With语句
2015/02/02 Python
python数据类型_元组、字典常用操作方法(介绍)
2017/05/30 Python
Python决策树之基于信息增益的特征选择示例
2018/06/25 Python
使用APScheduler3.0.1 实现定时任务的方法
2019/07/22 Python
基于Python2、Python3中reload()的不同用法介绍
2019/08/12 Python
python3 dict ndarray 存成json,并保留原数据精度的实例
2019/12/06 Python
Python3 解决读取中文文件txt编码的问题
2019/12/20 Python
你不知道的葡萄干处理法、橙蜜处理法、二氧化碳酵母法
2021/03/17 冲泡冲煮
CSS3中的弹性布局em运用入门详解 1em等于多少像素
2021/02/08 HTML / CSS
html5中去掉input type date默认样式的方法
2018/09/06 HTML / CSS
Agoda中文官网:安可达(低价预订全球酒店)
2021/01/18 全球购物
软件测试笔试题
2012/10/25 面试题
迎接领导欢迎词
2014/01/11 职场文书
宿舍打麻将检讨书
2014/01/24 职场文书
争先创优演讲稿
2014/09/15 职场文书
世界地球日活动总结
2015/02/09 职场文书
2015小学语文教师个人工作总结
2015/05/20 职场文书
golang goroutine顺序输出方式
2021/04/29 Golang
MySQL获取所有分类的前N条记录
2021/05/07 MySQL
对象析构函数__del__在Python中何时使用
2022/03/22 Python
GPU服务器的多用户配置方法
2022/07/07 Servers