0

This is a problem that has been previously solved (cannot write file with full path in Python) however I followed the advice in the previous answer and it didn't work and that's why I'm posting this.

I'm trying to access a csv file to load into the pandas dataframe.

import os
output_path = os.path.join('Desktop/My_project_folder', 'train.csv')

This is returning:

IOError: File Desktop/My_project_folder/train.csv does not exist

edit: I don't understand because the train.csv file exists in my project folder.

5
  • 1
    Try giving it your full path. That should look something like '/Users/YOURUSERNAME/Desktop/My_project_folder' where YOURUSERNAME is what you get when you type whoami into terminal. Commented Dec 4, 2015 at 21:04
  • What's weird is that when I run it in terminal by going into python soandsofile.py I get that error however when I enter python and run the code line by line it executes... I'm thoroughly confused. I did add the full filepath however I'm still seeing the same error when trying to run the command python soandso.py .... hence why i deleted the post ... it's like ignoring the Users/username/ part of the url when i run it in as python soandso.py which is why i think it's failing Commented Dec 4, 2015 at 21:13
  • Can you insert a print os.getcwd() into your python script and rerun it using both methods to see what it outputs? Commented Dec 4, 2015 at 21:22
  • 1
    You need to make sure that you located in the right directory. It's better to pass full path to file for read_csv Commented Dec 4, 2015 at 21:23
  • Got it, thanks guys! Commented Dec 4, 2015 at 21:34

1 Answer 1

0

The os.path.join() function is platform agnostic meaning it can run across multiple OS (PC, Mac, Linux) without having the need to specify directories or subdirectories with forward or back slashes. Hence, simply separate paths and file names by commas:

myDir = '/path/to/Desktop/My_project_folder'
output_path = os.path.join(myDir, 'train.csv')

However, if Python script resides in same directory as data, have script detect its own path and then import data frame into pandas and avoiding hard-coding whole path names:

import os
import pandas as pd

# SET CURRENT DIRECTORY
cd = os.path.dirname(os.path.abspath(__file__))

traindf = read_csv(os.path.join(cd, 'train.csv'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.