python - 如何让 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
,但它没有奏效。
解决方案
正如我评论的那样,你不能抓住 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 指出,一些SyntaxError
s 仍然可以在这个 SO 答案中捕获更多信息。
推荐阅读
- javascript - 如何使用 jquery/javascript 访问 DOM 中的评论?
- eclipse - Eclipse RCP - 按钮监听器最佳实践
- go - 从嵌套块返回,范围问题
- html - 为什么这个标题不会居中?
- r - 如何在不创建新数据集的情况下在 R 中进行子集化时使用数学运算
- firebase - 如何可视化 Firebase 数据以进行分析?
- python - python语音识别库/pyaudio:刷新麦克风列表
- unity3d - Unity保存解析问题
- c++ - 为什么 wifstream.read 函数没有将数据读取到变量中?
- vb.net - 如何在 VB 中格式化打印报表的结构数组?