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!')
try:
man_file=open('man_data.txt','w')
other_file=open('other_data.txt','w')
print(man, file=man_file)
print(other, file=other_file)
man_file.close()
other_file.close()
except IOError:
print('File error.')
它不应该创建man_data和other_data文件吗?闲置中没有错误消息或任何类型的输入。
屏幕截图中的缩进与您的问题有所不同。在您的问题中,您声称您的代码是这样的(有些地方被删节了):
try:
# Do something
except IOError:
# Handle error
try:
# Write to man_data.txt and other_data.txt
except IOError:
# Handle error
但是您的屏幕快照显示您实际上运行了以下代码:
try:
# Do something
except IOError:
# Handle error
try:
# Write to man_data.txt and other_data.txt
except IOError:
# Handle error
第二个try
/except
块的整个部分都位于except
第一个/子句的子句中,因此只有在第一个try
块中有异常时才执行。解决方案是运行您所质疑的代码,即,使第二个try
/except
块不缩进,使其与第一个/块处于同一级别。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句