python - Pandas .read_excel : Accessing the home directory

标签 python pandas path

[找到解决方案]

我在尝试使用 pandas.read_excel 访问我的主目录时遇到了一些意外行为。

我要访问的文件位于

/users/isys/orsheridanmeth

这是 cd ~/ 带我去的地方。我要访问的文件是

'~/workspace/data/example.xlsx'

读取excel文件的以下工作(使用import pandas as pd):

df = pd.read_excel('workspace/data/example_.xlsx', 'Sheet1')

鉴于

df = pd.read_excel('~/workspace/data/example.xlsx', 'Sheet1')

给我以下错误:

df = pd.read_excel('~/workspace/data/example.xlsx', 'Sheet1')
Traceback (most recent call last):
  File "/users/is/ahlpypi/egg_cache/i/ipython-3.2.0_1_ahl1-py2.7.egg/IPython/core/interactiveshell.py", line 3035, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-397-4412a9e7c128>", line 1, in <module>
    df = pd.read_excel('~/workspace/data/example.xlsx', 'Sheet1')
  File "/users/is/ahlpypi/egg_cache/p/pandas-0.16.2_ahl1-py2.7-linux-x86_64.egg/pandas/io/excel.py", line 151, in read_excel
    return ExcelFile(io, engine=engine).parse(sheetname=sheetname, **kwds)
  File "/users/is/ahlpypi/egg_cache/p/pandas-0.16.2_ahl1-py2.7-linux-x86_64.egg/pandas/io/excel.py", line 188, in __init__
    self.book = xlrd.open_workbook(io)
  File "/users/is/ahlpypi/egg_cache/x/xlrd-0.9.2-py2.7.egg/xlrd/__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: '~/workspace/data/example.xlsx'

pandas.read_csv 但是当我使用 pd.read_csv('~/workspace/data/example.csv') 时有效。

我想继续使用这个文件的相对路径。任何解释为什么这不适用于 pandas.read_excel

使用xlrd

当使用 xlrd 时,我得到一个类似的错误:

import xlrd
xl = xlrd.open_workbook('~/workspace/data/example.xlsx')
Traceback (most recent call last):
  File "/users/is/ahlpypi/egg_cache/i/ipython-3.2.0_1_ahl1-py2.7.egg/IPython/core/interactiveshell.py", line 3035, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-403-90af31feff4b>", line 1, in <module>
    xl = xlrd.open_workbook('~/workspace/data/example.xlsx')
  File "/users/is/ahlpypi/egg_cache/x/xlrd-0.9.2-py2.7.egg/xlrd/__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: '~/workspace/data/example.xlsx'

[解决方案]

from os.path import expanduser as ospath
df = pd.read_excel(ospath('~/workspace/data/example.xlsx'), 'Sheet1')

最佳答案

我相信 ~ 是由 shell 扩展的 - 在这种情况下,您的代码实际上是在尝试打开以 ~ 开头的路径。奇怪的是,这不起作用。 :-)

首先尝试通过 os.path.expanduser() 运行路径 - 这应该可以将 ~ 变量扩展为实际值。

您可能还想查看 os.path.expandvars()

希望对你有帮助

关于python - Pandas .read_excel : Accessing the home directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38476733/

相关文章:

python - 检查字符串是否与 python 中的模式匹配的最有效方法?

python - 从子目录导入模块

xml - 从 CLOB 中的 XML,到带有路径列表的 Oracle 表

java - 从代码更改 Tomcat Webapp 目录

python - 为什么我得到这个 NameError : name 'url_for' is not defined?

python - 如何在 pytorch 中将 2D 数据加载到 LSTM 中

python - 对条形图上显示的条形进行排序和限制数量

python - 关于 Gmsh Python API 的问题

python - 如何有效地映射 pandas DataFrame 上的转换

pandas - 我应该使用哪种可视化图?