Head First Python学习(第四章)

时间:2022-10-28 21:04:16

代码1

man=[]
other=[]
try:
    data=open('C:/sers/iWM/Desktop/学习/python学习/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)

结果1

The datafile is missing!
[]
[]

代码2

import os
os.chdir('C:/Users/iWM/Desktop/学习/python学习')
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!')

print (man)
print (other)

结果2

['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]

知识点:从文件中读数据时,先把路径切换到文件所在路径。