从零学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爬取Coursera课程资源的详细过程
Nov 04 Python
python开发之str.format()用法实例分析
Feb 22 Python
python3 图片referer防盗链的实现方法
Mar 12 Python
对Tensorflow中的变量初始化函数详解
Jul 27 Python
Python + selenium + requests实现12306全自动抢票及验证码破解加自动点击功能
Nov 23 Python
详解python解压压缩包的五种方法
Jul 05 Python
Django 外键的使用方法详解
Jul 19 Python
详解用python生成随机数的几种方法
Aug 04 Python
基于Python检测动态物体颜色过程解析
Dec 04 Python
OpenCV 表盘指针自动读数的示例代码
Apr 10 Python
Python生成器传参数及返回值原理解析
Jul 22 Python
python 5个实用的技巧
Sep 27 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
用文本文件制作留言板提示(下)
2006/10/09 PHP
php xml文件操作代码(一)
2009/03/20 PHP
解析php中memcache的应用
2013/06/18 PHP
在 Laravel 中动态隐藏 API 字段的方法
2019/10/25 PHP
javascript 获取元素位置的快速方法 getBoundingClientRect()
2009/11/26 Javascript
ECMAScript6的新特性箭头函数(Arrow Function)详细介绍
2014/06/07 Javascript
Nodejs sublime text 3安装与配置
2014/06/19 NodeJs
javascript实现类似于新浪微博搜索框弹出效果的方法
2015/07/27 Javascript
轻松学习jQuery插件EasyUI EasyUI实现拖动基本操作
2015/11/30 Javascript
三分钟带你玩转jQuery.noConflict()
2016/02/15 Javascript
js控制div层的叠加简单方法
2016/10/15 Javascript
PHP实现本地图片上传和验证功能
2017/02/27 Javascript
详细分析JS函数去抖和节流
2017/12/05 Javascript
微信小程序实现多选功能
2018/11/04 Javascript
微信小程序实现商品属性联动选择
2019/02/15 Javascript
vue实现商城秒杀倒计时功能
2019/12/12 Javascript
python排序方法实例分析
2015/04/30 Python
在django admin详情表单显示中添加自定义控件的实现
2020/03/11 Python
Python实现从N个数中找到最大的K个数
2020/04/02 Python
tensorflow使用freeze_graph.py将ckpt转为pb文件的方法
2020/04/22 Python
tensorflow实现从.ckpt文件中读取任意变量
2020/05/26 Python
详解css3 Transition属性(平滑过渡菜单栏案例)
2017/09/05 HTML / CSS
CSS3实现王者匹配时的粒子动画效果
2019/04/12 HTML / CSS
简单的HTML5初步入门教程
2015/09/29 HTML / CSS
手机端用rem+scss做适配的详解
2017/11/15 HTML / CSS
VLAN和VPN有什么区别?分别实现在OSI的第几层?
2014/12/23 面试题
十佳青年个人事迹材料
2014/01/28 职场文书
学生会竞聘书范文
2014/03/31 职场文书
升学宴主持词
2014/04/02 职场文书
产品生产计划书
2014/05/07 职场文书
管理建议书范文
2014/05/13 职场文书
战略合作意向书
2014/07/29 职场文书
研究生简历自我评价范文
2014/09/13 职场文书
四风问题个人对照检查材料
2014/09/26 职场文书
虎兄虎弟观后感
2015/06/12 职场文书
2016学习医德医风心得体会
2016/01/25 职场文书