xlrd python不起作用 - "语法错误"

时间:2014-11-29 22:47:22

标签: python excel xlrd spyder pythonxy

我试图熟悉xlrd,所以我将一个例子复制到我的IDE(spyder)中。我使用python(x,y)2.7.6.1

这是我的例子

import xlrd
import os

filename=os.path.join("C:/","Desktop/myfile"):
book = xlrd.open_workbook(filename)
print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()
sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
for rx in range(sh.nrows):
    print sh.row(rx)

正如您所看到的,我听取了关于SE here的建议,但它仍然无效(语法错误)。建议here我已经在接受的答案中给出了os.path.join()中的内容。

这是错误日志:

runfile('C:/Users/PC/.spyder2/.temp.py', wdir=r'C:/Users/PC/.spyder2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
  File "C:/Users/PC/.spyder2/.temp.py", line 12
    filename=os.path.join("C:/","/Users/PC/Desktop/myfile"):
                                                      ^

SyntaxError:语法无效

UPDATE 现在,当我用&#34;加入&#34;我有另一个语法错误。就是这样:

runfile('C:/Users/PC/.spyder2/.temp.py', wdir=r'C:/Users/PC/.spyder2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
 File "C:/Users/PC/.spyder2/.temp.py", line 13, in <module>
    book = xlrd.open_workbook(filename)
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: 'C:/Users/PC/Desktop/myfile'

我做错了什么?我该怎么做呢?

3 个答案:

答案 0 :(得分:1)

语法错误是第一行末尾不应该有:

&#34;没有这样的文件或目录&#34;错误是因为桌面不是位于&#34; C:/ Desktop&#34;的目录。实际上有多个目录,其内容显示在桌面上,但可能你想要的是&#34; C:/ Users / USERNAME / Desktop /&#34;,其中USERNAME当然是你的用户名机。

如果您想要访问主目录(即不仅仅是您的主目录,您需要运行该脚本的主目录),那么您可以访问HOMEDRIVE和HOMEPATH环境变量。

答案 1 :(得分:1)

这是连接线末端的冒号。它不应该存在。

答案 2 :(得分:0)

正如痴呆hedgehog和Steve Jessop所建议我必须转换以下行

filename=os.path.join("C:/","Desktop/myfile"):

filename=os.path.join("C:/","/Users/PC/Desktop/myfile.xls")

所以我只需删除冒号,编写正确的目录并编写myfile.xls而不仅仅是myfile。