不再怀疑

导航

第三章《文件与异常》

1.文件的打开:

路径查看

import os

os.getcwd()

进入目录:

os.chdir(路径)

打开:

data=open('sketch.txt')

2.读取文件:

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='')

注:该文件用:分割,其中split是用于分割部分,后面的1标识几位

 

2.异常:

try:

except

try:
data = open('sketch.txt')

for each_line in data:
try:
if not each_line.find(':')==-1:
(role,line_spoken) = each_line.split(':',1)
print(role,end='')
print(' said: ',end='')
print(line_spoken,end='')
except:
pass
except:
print('The data file is missing')

 

posted on 2017-01-10 16:38  不再怀疑  阅读(109)  评论(0编辑  收藏  举报