Python学习_从文件读取数据和保存数据

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

运用Python中的内置函数open()与文件进行交互

在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例:

新建IDLE会话,首先导入os模块,并将工作目录却换到包含文件“sketch.txt”的文件夹,如C:\\Python33\\HeadFirstPython\\chapter3

>>>importos>>> 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 roomforan argument?>>>print(data.readline(),end='')

Other Man: I've told you once.

回到文件起始位置,使用for语句处理文件中的每行,最后关闭文件:

>>> data.seek(0)#使用seek()方法回到文件起始位置0>>>foreach_lineindata:print(each_line,end='')

Man: Is this the right roomforan 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 didnot!

Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?Man: Ah! (taking out his walletandpaying) Just the five minutes.

Other Man: Just the five minutes. Thank you.

Other Man: Anyway, I did.

Man: You most certainly didnot!

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 itis!

Man: No it isn't!(pause)

Man: It's just contradiction!Other Man: No it isn't!Man: It IS!

Other Man: ItisNOT!

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, thisisfutile!!

(pause)

Other Man: No it isn't!Man: Yes itis!>>> data.close()

View Code

读取文件后,将不同role对应数据分别保存到列表man和other:

importosprint(os.getcwd())

os.chdir('C:\Python33\HeadFirstPython\chapter3')

man=[]#定义列表man接收Man的内容other=[]#定义列表other接收Other Man的内容try:

data=open("sketch.txt")foreach_lineindata:try:

(role, line_spoken)=each_line.split(':', 1)

line_spoken=line_spoken.strip()ifrole=='Man':

man.append(line_spoken)elifrole=='Other Man':

other.append(line_spoken)exceptValueError:passdata.close()exceptIOError:print('The datafile is missing!')print(man)print(other)

Tips:

使用open()方法打开磁盘文件时,默认的访问模式为r,表示读,不需要特意指定;

要打开一个文件完成写,需要指定模式w,如data=open("sketch.txt","w"),如果该文件已经存在则会清空现有内容;

要追加到一个文件,需要指定模式a,不会清空现有内容;

要打开一个文件完成写和读,且不清空现有内容,需要指定模式w+;

例如,将上例中保存的man和other内容以文件方式保存时,可修改如下:

1importos2print(os.getcwd())3os.chdir('C:\Python33\HeadFirstPython\chapter3')4man=[]5other=[]67try:8data=open("sketch.txt")9foreach_lineindata:10try:11(role, line_spoken)=each_line.split(':', 1)12line_spoken=line_spoken.strip()13ifrole=='Man':14man.append(line_spoken)15elifrole=='Other Man':16other.append(line_spoken)17exceptValueError:18pass19data.close()20exceptIOError:21print('The datafile is missing!')2223try:24man_file=open('man.txt','w')#以w模式访问文件man.txt25other_file=open('other.txt','w')#以w模式访问文件other.txt26print(man, file=man_file)#将列表man的内容写到文件中27print(other, file=other_file)28exceptIOError:29print('File error')30finally:31man_file.close()32other_file.close()

但是第26行print()为什么会报错?“syntax error while detecting tuple”

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航