首页 > 解决方案 > 如何让 try/except 正常工作

问题描述

我正在尝试解析大量文件以在一张表中获取一些信息。这是我的脚本:

import pandas as pd
import numpy as np
M1 = pd.DataFrame(Test,columns=['Test'])

for sample in samples:
    with open("file/"+sample+".txt") as f:
        c=0
        tpm=[]
        for line in f:
            c+=1
#                if c==1:
#                    if line.split('/')[1].split('.')[0]!='abc':
#                        break
            if c>2 and line.startswith('gene'):
                try:
                    return tpm.append(int(line.rstrip().split('\t')[6])/int(line.rstrip().split('\t')[5])*1000)
                except ZeroDivisionError:
                    return 0

M1[Test]=tpm/np.sum(tpm)*1000000
M=M1
M=M.fillna(0)
M.index=M['Test']
M.to_csv('M.xls',index=False,sep='\t')'

没有包含的行try:except ZeroDivisionError它可以工作,但我得到了 ZeroDivision 错误,结果不能用于下一行。所以我想在 *.txt 文件中遇到 0 时添加 0 而不是除法。

在这个脚本中,我遇到了一个'return' outside function语法错误

我尝试了许多方法,例如添加try之前for line in f:或添加except: pass,但它没有奏效。

标签: python

解决方案


正如我评论的那样,你不能抓住 a SyntaxError,你不应该return在函数之外使用语句。如果您的意图是在发生 aZeroDivisionError时添加 0,您可以在部分中更改代码except。这样,0如果您遇到 a ,您将添加 a ZeroDivisionError

try:
    tpm.append(int(line.rstrip().split('\t')[6])/int(line.rstrip().split('\t')[5])*1000)
except ZeroDivisionError:
    tpm.append(0)

编辑:@chepner 指出,一些SyntaxErrors 仍然可以在这个 SO 答案中捕获更多信息


推荐阅读