简体   繁体   English

Python:打开Excel文件时观察到错误

[英]Python: Error observed while opening an excel file

I am trying to open and read an Excel file using Python with the following code: 我正在尝试使用以下代码使用Python打开和读取Excel文件:

if __name__ == '__main__':
    print len(sys.argv)
    if len(sys.argv) > 1:
        print len(sys.argv)
        fp = sys.argv[1]  
        fn = sys.argv[2]
    else:
        fn = raw_input('Please enter the file path of your excel file: ')
        print 'ok'
    fw = fn[0:12] + 'Translated' + fn[15:]
    print 'ok1'

    fr = open('%s\%s' % (fp, fn), 'r')
    fw = open('%s\%s' % (fp, fw), 'wb')

Unfortunately, I get the following error: 不幸的是,我收到以下错误:

Traceback (most recent call last):
  File "C:\EclipseWorkspaces\PY2.7\PXBCM1.5\src\Translator.py", line 43, in <module>
    fr = open('%s\%s'% (fp,fn),'r')
NameError: name 'fp' is not defined

I do not understand what's wrong with my code. 我不明白我的代码有什么问题。

As the error message suggests, the name fp is not defined. 如错误消息所示,未定义名称fp Looking at your code, I assume that your code branched in the else condition and thus fp was literally not defined. 查看您的代码,我假设您的代码在else条件下分支,因此fp实际上没有定义。

If we look at an extract of your code: 如果我们看一下您的代码摘录:

if len(sys.argv) > 1:
    print len(sys.argv)
    fp = sys.argv[1]  # <-- fp is defined: GOOD
    fn = sys.argv[2]
else:
    fn = raw_input('Please enter the file path of your excel file: ')
    print 'ok'
    # <-- fp was not defined: BAD

So just make sure that by the time you call the open function, both fp and fn were defined, with statements like fp = … and fn = … . 因此,只需确保在调用open函数时,就已经定义了fpfn ,并使用了fp = …fn = …类的语句。


Apart from that, your code presents one major flaw: you use the condition if len(sys.argv) > 1 but it just tells you that sys.argv is at least of length 2. Thus, it allows you to access safely sys.argv[0] (the 1st element) and sys.argv[1] (the 2nd element) but you cannot assume that sys.argv[2] exists. 除此之外,您的代码还存在一个主要缺陷: if len(sys.argv) > 1 ,则使用条件if len(sys.argv) > 1但它只是告诉您sys.argv的长度至少为2。因此,它使您可以安全地访问sys.argv[0] (第一个元素)和sys.argv[1] (第二个元素),但是您不能假定sys.argv[2]存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM