准备工作
创建一个文件夹,存放sketch.txt 文件
sketch.txt 文件内容如下
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!
>>> import os
>>> os.getcwd()
'C:\\Users\\gaomy\\AppData\\Local\\Programs\\Python\\Python36'
>>> os.chdir('D:\Study\IT_Python\Demo\HeadFirstPython\chapter3')
>>> os.getcwd()
'D:\Study\\IT_Python\\Demo\\HeadFirstPython\\chapter3'
>>> data.open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> data.seek(0)
0
功能代码
- 方法一:(额外代码)
打开文件,处理文件中的每一行,不过只是在确定数据行符合所需的格式之后才进行处理,这是通过检查数据行中是否有一个“:”字符来做到的。如果找到了“:”,则处理这个数据行,否则就将这个数据行忽略。所有工作完成时,关闭数据文件。如果文件未找到,最后你会得到一个友好的消息。
data = open('sketch.txt')
for each_line in data:
if not each_line.find(':') == -1:
(role,line_spoken) = each_line.split(':',1)
print(role,end='')
print('said: ',end='')
print(line_spoken,end='')
data.close()
- 方法二:(异常处理程序)
打开一个数据文件,处理这个文件中的各个数据行,抽取感兴趣的数据,并显示在屏幕上完成后关闭文件,如果出现任何一场,这个代码会进行处理。
data = open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
print(role,end='')
print('said: ',end='')
print(line_spoken,end='')
except:
pass
data.close()
- 方法三(特定指定异常)
异常处理代码设计为处理一种特定类型的错误,并在except代码行上指定错误类型。这样就可以把一般化的异常处理代码转变为具有特定性。
data = open('sketch.txt')
try:
for each_line in data:
try:
(role,line_spoken)=each_line.split(':')
print(role,end='')
print('said: ',end='')
print(line_spoken,end='')
except ValueError:
pass
data.close()
except IOError:
print('The data file is missing!')
要点
- 对文件进行简单的操作:
- 当前目录:
os.getcwd()
- 跳转到指定目录:
os.chdir('D:\Study\IT_Python\Demo\HeadFirstPython\chapter3')
- 打开文件:
data.open('sketch.txt')
- 读取文件:
print(data.readline(),end='')
- 回到文件起始位置:
data.seek(0)
- 将字符串分解为一个子串列表:
split()
- Python中不可改变的常量列表称为元组(Tuple)。一旦将列表数据赋给一个元组,就不能再改变。元组是不可改变的。
- 数据不符合期望的格式时会出现ValueError。
- 数据无法正常访问时会出现IOError(例如:数据文件被移走或重命名)。
- find()方法会在一个字符串中查找一个特定子串。
- not 关键字将一个条件取反。
- try/except语句提供了一个异常处理机制,从而保护可能导致运行时错误的某些代码行。
- pass语句就是Python的空语句或null语句,它啥也不做。