拓展:文件及错误处理1

拓展:文件及错误处理1

 该部分为Head first python 第二部分内容。视频教程并未讲到,故作为拓展。
依样画葫芦来几段加深印象。
 python从文件读取数据 open()方法
python中标准‘打开-处理-关闭’代码:

the_file = open('sketch.txt')
# do something with the data
#in 'the_file' 
the_file.close()

需要导入os模块查看python目录位置
 
>>> import os        #从标准库导入os
>>> os.getcwd()
'D:\Python33'            #当前的工作目录
>>> os.chdir ('f:\python')        #修改为包含数据文件的文件夹
>>> os.getcwd()                        #确认现在在正确的目录下
'f:\python'    
>>> data = open('sketch.txt')        #把打开的文件内容赋值给data
>>> print (date.readline(), end = '')        #使用readline()方法从文件中获取一个数据行,然后打印出来看看。
Man: Is this the right room for an argument?
>>> print (date.readline(), end = '')
Other Man: I've told you once.
>>> print (date.readline(), end = '')
Man: No you haven't!
>>> print (date.readline(), end = '')
Other Man: Yes I have.
>>> 
 读取成功
返回到文件起始位置,使用for循环处理文件中的每一行: 
>>> data.seek(0)            #用seek()方法返回到文件的起始位置
0
>>> for each_line in data:                #标准的for循环迭代
    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!
 
...
 
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()        #养成良好的习惯,处理完文件就要将它关闭。
 
根据需要抽取数据行中的各个部分,比如,人物:对话内容。其中明显的分割符号是冒号‘:’,那么可以用split()方法实现。
如: each_line.split(':') 调用split()并关联each_line字符串,将字符串用‘:’分开。
 
>>> each_line.split (':')
['Man', ' Yes it is! ']
 
split()方法返回一个字串符列表,这会赋至一个目标标识符列表,称之为 多重赋值(multiple assignment)如:
(role,line_spoken) = each_line.split(':')
照着书本这样写:
 
>>> for each_line in data:
    (role, line_spoken) = each_line.split(':')
    print(role, end = '')
    print('  said:  ', end = '')
    print(line_spoken , end = '')
 
    
>>> 
 怎么回事?跟结果不一样啊。。。输入之后没反应,直接返回shell命令行。。。
摸了很久才知道,原来文件刚才被读取过关闭了,要重新打开 
 
>>> data = open('sketch.txt')
>>> for each_line in data:
    (role, line_spoken) = each_line.split(':')
    print(role , end = '')
    print ('  said:  ', end = '')
    print (line_spoken, end = '')
 
    
Man  said:   Is this the right room for an argument?
Other Man  said:   I've told you once.
Man  said:   No you haven't!
Other Man  said:   Yes I have.
Man  said:   When?
Other Man  said:   Just now.
Man  said:   No you didn't!
Other Man  said:   Yes I did!
Man  said:   You didn't!
Other Man  said:   I'm telling you, I did!
Man  said:   You did not!
Other Man  said:   Oh I'm sorry, is this a five minute argument, or the full half hour?
Man  said:   Ah! (taking out his wallet and paying) Just the five minutes.
Other Man  said:   Just the five minutes. Thank you.
Other Man  said:   Anyway, I did.
Man  said:   You most certainly did not!
Traceback (most recent call last):
  File "<pyshell#64>", line 2, in <module>
    (role, line_spoken) = each_line.split(':')
ValueError: too many values to unpack (expected 2)
 
这下跟教材里的范例一模一样了。。它的print有三行。。。我在想能不能格式化字符串用%s代替输出?! 
>>> data = open('sketch.txt')
>>> for each_line in data:
    (role, line_spoken) = each_line.split(':')
    print('%s said: %s' % (role, line_spoken) , end = '' )
 
    
Man said:  Is this the right room for an argument?
Other Man said:  I've told you once.
Man said:  No you haven't!
Other Man said:  Yes I have.
Man said:  When?
Other Man said:  Just now.
Man said:  No you didn't!
Other Man said:  Yes I did!
Man said:  You didn't!
Other Man said:  I'm telling you, I did!
Man said:  You did not!
Other Man said:  Oh I'm sorry, is this a five minute argument, or the full half hour?
Man said:  Ah! (taking out his wallet and paying) Just the five minutes.
Other Man said:  Just the five minutes. Thank you.
Other Man said:  Anyway, I did.
Man said:  You most certainly did not!
Traceback (most recent call last):
  File "<pyshell#76>", line 2, in <module>
    (role, line_spoken) = each_line.split(':')
ValueError: too many values to unpack (expected 2)
>>> 
这叫学以致用。
看到这代码中返回一个Traceback的错误,类型是ValueError:大概是说给的值多了,前面spilt()的方法只能用冒号分解成两部分。
这是教材里的范例。下节课将分析这些错误。
原文地址:https://www.cnblogs.com/fishdm/p/3574091.html