从零学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的Django框架中的缓存控制
Jul 24 Python
Python 功能和特点(新手必学)
Dec 30 Python
从零开始学Python第八周:详解网络编程基础(socket)
Dec 14 Python
使用Python3 编写简单信用卡管理程序
Dec 21 Python
python3获取两个日期之间所有日期,以及比较大小的实例
Apr 08 Python
python使用pygame框架实现推箱子游戏
Nov 20 Python
python 内置模块详解
Jan 01 Python
Python Pandas数据结构简单介绍
Jul 03 Python
Python根据服务获取端口号的方法
Sep 25 Python
Linux安装Python3如何和系统自带的Python2并存
Jul 23 Python
Python爬虫逆向分析某云音乐加密参数的实例分析
Dec 04 Python
python数据库批量插入数据的实现(executemany的使用)
Apr 30 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 Undefined index的问题
2009/06/01 PHP
php中输出json对象的值(实现方法)
2018/03/07 PHP
js中的window.open返回object的错误的解决方法
2009/08/15 Javascript
读jQuery之一(对象的组成)
2011/06/11 Javascript
YUI Compressor压缩JavaScript原理及微优化
2013/01/07 Javascript
JavaScript 命名空间 使用介绍
2013/08/29 Javascript
js函数名与form表单元素同名冲突的问题
2014/03/07 Javascript
javascript获取checkbox复选框获取选中的选项
2014/08/12 Javascript
jQuery获取iframe的document对象的方法
2014/10/10 Javascript
原生JavaScript编写canvas版的连连看游戏
2016/05/29 Javascript
一个仿微博登陆邮箱提示框js开发案例
2016/07/28 Javascript
利用JavaScript阻止表单提交的两种方法
2016/08/11 Javascript
jsp 自动编译机制详细介绍
2016/12/01 Javascript
js实现淡入淡出轮播切换功能
2017/01/13 Javascript
JavaScript数组和对象的复制
2017/03/21 Javascript
详解Node.js 命令行程序开发教程
2017/06/07 Javascript
vue实现页面加载动画效果
2017/09/19 Javascript
JS正则表达式完美实现身份证校验功能
2017/10/18 Javascript
手把手教你 CKEDITOR 4 实现Dialog 内嵌 IFrame操作详解
2019/06/18 Javascript
vue路由拦截器和请求拦截器知识点总结
2019/11/08 Javascript
Python  pip安装lxml出错的问题解决办法
2017/02/10 Python
Python yield与实现方法代码分析
2018/02/06 Python
Python设计模式之适配器模式原理与用法详解
2019/01/15 Python
Python OS模块实例详解
2019/04/15 Python
django解决订单并发问题【推荐】
2019/07/31 Python
Pyecharts 动态地图 geo()和map()的安装与用法详解
2020/03/25 Python
突破canvas语法限制 让他支持链式语法
2012/12/24 HTML / CSS
html5中canvas图表实现柱状图的示例
2017/11/13 HTML / CSS
印度购买眼镜和太阳镜网站:Coolwinks
2018/09/26 全球购物
美国便宜的横幅和标志印刷在线:Best of Signs
2019/05/29 全球购物
FC-Moto美国:欧洲最大的摩托车服装和头盔商店之一
2019/08/24 全球购物
幼儿园元旦活动感言
2014/03/02 职场文书
诚信贷款承诺书
2014/05/30 职场文书
SpringCloud Function SpEL注入漏洞分析及环境搭建
2022/04/08 Java/Android
springboot读取nacos配置文件
2022/05/20 Java/Android
windows11选中自动复制怎么开启? Win11自动复制所选内容的方法
2022/07/23 数码科技