为什么这个python代码中没有显示输出?

时间:2016-10-12 14:21:24

标签: python python-3.x

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文件吗? 空闲时没有错误消息或任何类型的输入。

enter image description here

1 个答案:

答案 0 :(得分:2)

屏幕截图中的缩进与您的问题不同。在您的问题中,您声称您的代码是这样的(有些位被修剪掉):

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中有异常时才会执行它。 1}}阻止。解决方案是运行您问题中的代码,即取消第二个try / except块,以使其与第一个块处于同一级别。

相关问题