[英]How can I import a csv from another folder in python?
I have a script in python, I want to import a csv from another folder.我在 python 中有一个脚本,我想从另一个文件夹导入 csv。 how can I do this?
我怎样才能做到这一点? (for example, my.py is in a folder and I whant to reach the data from the desktop)
(例如,my.py 在一个文件夹中,我想从桌面获取数据)
First of all, you need to understand how relative and absolute paths work.首先,您需要了解相对路径和绝对路径是如何工作的。
I write an example using relative paths
.我写了一个使用
relative paths
的例子。 I have two folders in desktop called scripts
which includes python files and csvs
which includes csv files.我在桌面上有两个文件夹,称为
scripts
,其中包括 python 文件和csvs
,其中包括 csv 文件。 So, the code would be:因此,代码将是:
df = pd.read_csv('../csvs/file.csv)
The path means:路径的意思:
..
(previous folder, in this case, desktop folder)...
(上一个文件夹,在本例中为桌面文件夹)。
/csvs
(csvs folder)./csvs
(csvs 文件夹)。
/file.csv
(the csv file)./file.csv
文件)。
If you are on Windows:如果您使用的是 Windows:
Location:
tag that has a structure similar to this: C:\Users\<user_name>\Desktop
Location:
标签,其结构类似于: C:\Users\<user_name>\Desktop
file_path = r'C:\Users\<your_user_name>\Desktop\<your_file_name>.csv'
df = pd.read_csv(file_path)
Obviously, always try to use relative paths instead of absolute paths like this in your code.显然,始终尝试在代码中使用相对路径而不是像这样的绝对路径。 Investing some time into learning the
Pathlib
module would greatly help you.花一些时间学习
Pathlib
模块会对您有很大帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.