简体   繁体   English

如何在单独的父文件夹中读取 csv 文件?

[英]How do I read a csv file in a seperate parent folder?

I have a directory with the following subdirectories我有一个包含以下子目录的目录

|---Data
|
|---Notebooks

The Data directory contains csv files, while the Notebooks directory contains my Jupyter notebook files. Data目录包含 csv 文件,而Notebooks目录包含我的 Jupyter 笔记本文件。 How do I access the file from the Data directory with a notebook at the Notebooks directory?如何使用Notebooks目录中的笔记本从Data目录访问文件?

My initial idea was this:我最初的想法是这样的:

df = pd.read_csv('../Data/csvFile')

However the code block renders a file not found error in Pandas.但是,代码块在 Pandas 中呈现file not found错误。

The path you'll need will be relative to the directory you're running the Python process from normally, but you can use the following trick to make it relative to a file you're running instead:您需要的路径将与您正常运行 Python 进程的目录相关,但您可以使用以下技巧使其相对于您正在运行的文件:

from pathlib import Path

df = pd.read_csv(Path(__file__).parent/'Data'/'csvFile')

However the __file__ variable is not defined in Jupyter notebooks, so you'll have to use this hack instead to get the directory the notebook is in:但是__file__变量没有在 Jupyter 笔记本中定义,因此您必须使用此 hack 来获取笔记本所在的目录:

from pathlib import Path

df = pd.read_csv(Path(globals()['_dh'][0])/'Data'/'csvFile')

Note that this hack only works when running from Jupyter.请注意,此 hack 仅在从 Jupyter 运行时有效。 Unfortunately I don't have a one-size-fits-all approach, unless you count detecting if you're in Jupyter, and then selecting which method you'll use based off of that.不幸的是,我没有一刀切的方法,除非您计算检测您是否在 Jupyter 中,然后根据此选择您将使用的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM