简体   繁体   English

如何从 python 中的另一个文件夹导入 csv?

[英]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:

  • Right-click on the file on your desktop, and go to its properties.右键单击桌面上的文件,然后 go 到它的属性。
  • You should see a Location: tag that has a structure similar to this: C:\Users\<user_name>\Desktop您应该会看到一个Location:标签,其结构类似于: C:\Users\<user_name>\Desktop
  • Then you can define the file path as a variable in Python as:然后您可以在 Python 中将文件路径定义为变量:
file_path = r'C:\Users\<your_user_name>\Desktop\<your_file_name>.csv'
  • To read it:要阅读它:
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.

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