-1

我正在尝试熟悉 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 的建议,但它仍然不起作用(语法错误)。正如这里所建议那样,我已经以接受的答案中给出的方式在 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:无效的语法

更新现在,当我用“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 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'

我究竟做错了什么?我应该怎么做?

4

3 回答 3

1

It's the colon at the end of the join line. It shouldn't be there.

于 2014-11-29T23:10:21.230 回答
1

:语法错误是第一行的末尾应该没有。

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

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

于 2014-11-29T22:59:06.220 回答
0

正如痴呆的刺猬和史蒂夫杰索普所建议的那样,我必须转换以下行

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

进入

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

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

于 2014-11-30T09:35:28.107 回答