0

Currently, I have created a code that makes graphs from data in .csv files. However, I can only run the code if that code is present in the folder with the csv files. How can I make the the script file so that it doesn't have to be in the same directory as the .csv files. Also, I would like that same script to read every csv file in that other directory.

This is what I was using before:

directory = ""
listing = os.listdir(directory)
for files in listing:
   if files.endswith('.csv'):  
        df=pd.read_csv(files)
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • 1
    Google for "python change directory" yields [this StackOverflow question](http://stackoverflow.com/questions/431684/how-do-i-cd-in-python). – larsks Jul 24 '13 at 16:42

2 Answers2

2

Just replace directory = "" with directory="../your-path-to-csv-files". Here is a complete example:

directory = "../your-path-to-csv-files"
listing = os.listdir(directory)
for files in listing:
   if files.endswith('.csv'):  
        full_name = os.path.join(directory,files)
        df=pd.read_csv(full_name)
dkar
  • 2,113
  • 19
  • 29
0

I've built for such purposes a little function, which calculates paths of data relative to the execution-place of the python-file:

import os
def getPathToData():
    path = os.path.split(os.path.abspath(__file__))
    path = os.path.abspath(path[0])
    path = path + "/data/"
    return path

Maybe this snippet can help you.

Themerius
  • 1,861
  • 1
  • 19
  • 33