oli*_*rsm 5 python path pandas
[解决方案]
尝试使用时访问我的主目录时遇到了一些意外的行为pandas.read_excel.
我想访问的文件可以在以下位置找到
/users/isys/orsheridanmeth
Run Code Online (Sandbox Code Playgroud)
这是cd ~/我的所在.我想访问的文件是
'~/workspace/data/example.xlsx'
Run Code Online (Sandbox Code Playgroud)
以下工作读取excel文件(使用import pandas as pd):
df = pd.read_excel('workspace/data/example_.xlsx', 'Sheet1')
Run Code Online (Sandbox Code Playgroud)
而
df = pd.read_excel('~/workspace/data/example.xlsx', 'Sheet1')
Run Code Online (Sandbox Code Playgroud)
给我以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
[解]
from os.path import expanduser as ospath
df = pd.read_excel(ospath('~/workspace/data/example.xlsx'), 'Sheet1')
Run Code Online (Sandbox Code Playgroud)
小智 6
我相信它~是由shell扩展的 - 在这种情况下,你的代码实际上是试图打开一个开头的路径~.奇怪的是,这不起作用.:-)
首先尝试运行路径os.path.expanduser()- 这应该可以将~变量扩展为实际值.
您可能还想查看os.path.expandvars().
希望有所帮助