从零学python系列之从文件读取和保存数据

时间:2021-02-11 01:51:29 

在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,open()
0
投稿

猜你喜欢

  • sqlserver合并DataTable并排除重复数据的通用方法分享

    2012-01-05 18:59:56
  • 详解python播放音频的三种方法

    2021-12-16 09:19:11
  • ADSI+ASP添加IP到IIS禁止访问列表中

    2011-04-02 10:42:00
  • python中使用xlrd、xlwt操作excel表格详解

    2023-06-25 03:59:51
  • Python 中的lambda匿名函数和三元运算符

    2023-04-21 05:22:18
  • python数据类型强制转换实例详解

    2022-02-08 05:22:43
  • asp如何连接MYSQL数据库?

    2010-01-01 15:49:00
  • Python基于TensorFlow接口实现深度学习神经网络回归

    2022-07-17 22:38:28
  • 用户体验的误解

    2008-07-15 12:31:00
  • PHP工厂模式Factory Pattern的实现及特点

    2023-05-25 05:19:24
  • 说说回车键触发表单提交的问题

    2009-02-03 13:25:00
  • FrontPage 2000主页设计问与答

    2008-08-02 12:37:00
  • python实现斐波那契递归函数的方法

    2022-03-22 19:54:49
  • python3实现读取chrome浏览器cookie

    2023-10-18 13:18:44
  • 利用Python上传日志并监控告警的方法详解

    2022-08-23 15:31:01
  • Python基础面向对象之继承与派生详解

    2022-04-20 11:58:53
  • python装饰器三种装饰模式的简单分析

    2022-06-26 17:29:46
  • Oracle的数据字典技术简析

    2010-07-20 13:03:00
  • asp最简单的生成验证码代码

    2011-03-07 11:05:00
  • ASP+ajax注册即时提示程序代码

    2011-02-05 11:25:00
  • asp之家 网络编程 m.aspxhome.com