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

在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 osprint(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 osprint(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”,有大神能给解惑一下不

Posted in 未分类

发表评论