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)
CodePudding user response:
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).
CodePudding user response:
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.
