1
from xlrd import *

book = open_workbook("File_1.xls")

#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 

デスクトップにあるファイルを読み込んでいますが、Python で記述されたスクリプトを実行するとエラーが発生します

  Traceback (most recent call last):
  File "C:\Python26\ReadXLS.py", line 6, in <module>
  book = open_workbook("File_1.xls")
  File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 449, in open_workbook
  ragged_rows=ragged_rows,
 File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 941, in biff2_8_load
 f = open(filename, open_mode)
  IOError: [Errno 2] No such file or directory: 'File_1.xls'
4

3 に答える 3

2

cd Desktopファイルが存在しないというエラー メッセージが表示されるため、Python を実行する前に次のようにする必要があります。

No such file or directory: 'File_1.xls'

もう 1 つの修正方法は、Python ファイルを Excel ファイルと同じフォルダーに移動することです。

于 2012-06-21T04:53:59.880 に答える
1

パスの問題に直面している場合は、プログラムで現在のパスを見つけてみてください

>>> import os.path
>>> import os
>>> os.curdir
'.'
>>> os.path.abspath(os.curdir)
'/Users/xxxx/temp'
>>> 

Unix ではこのように表示されます。Windows では表示が異なります。

このようにして、それが現在のファイルが配置されている場所であるかどうかがわかります。

コード:

from xlrd import *
import os.path
import os
print os.path.abspath(os.curdir)

book = open_workbook("File_1.xls")
#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 
于 2012-06-21T05:44:39.613 に答える
1

スクリプトとファイルがディレクトリにあることを確認するか、Excel ファイルへの絶対パスを指定します。

また、ファイルを相対的に開こうとすると、Python インタープリターが初期化された現在の作業ディレクトリを使用して行われることに注意してください。

新しい xlsx 形式を使用する必要がある場合は、openpyxl http://packages.python.org/openpyxl/もお勧めします。

于 2012-06-21T05:00:16.027 に答える