简体   繁体   中英

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. how can I do this? (for example, my.py is in a folder and I whant to reach the data from the desktop)

First of all, you need to understand how relative and absolute paths work.

I write an example using relative paths . I have two folders in desktop called scripts which includes python files and csvs which includes csv files. 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).

/file.csv (the csv file).

If you are on Windows:

  • Right-click on the file on your desktop, and go to its properties.
  • You should see a Location: tag that has a structure similar to this: C:\Users\<user_name>\Desktop
  • Then you can define the file path as a variable in Python as:
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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