Python代码结构

时间:2015-03-25 17:14:08

标签: python python-3.x

我有一些我编写的Python 3.4代码可以正确执行但是当使用不同的IDE来帮助我找到错误时,我会在此代码片段中的赋值错误之前获得引用的变量:

if os.path.isfile(o.options_file):  # Make sure this really is a file.
    options = (csv.reader(open(o.options_file), delimiter='\t'))
else:
    exit("Options_File Not Found.  Check File Name and Path.")
count = 0
for line in options:
    count += 1

抛出错误的是options变量。这可以忽略,还是应该为选项分配Null值?

1 个答案:

答案 0 :(得分:2)

你可以反转测试:

if not os.path.isfile(o.options_file):  # Make sure this really is a file.
    exit("Options_File Not Found.  Check File Name and Path.")

options = (csv.reader(open(o.options_file), delimiter='\t'))
count = 0
for line in options:
    count += 1

这使得代码linting工具其他开发人员更加清楚,如果文件不存在,其余的代码将无法运行。