Reputation: 45
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.
Why is the code below wrong?
Here=os.path.dirname(os.path.abspath(__file__))
directory = "path of directory"
listing = os.listdir(directory)
for files in listing:
if files.endswith('.csv'):
full_name = os.path.join(Here,files)
df=pd.read_csv(full_name)
Upvotes: 0
Views: 144
Reputation: 8202
You are listing an empty directory (directory = ''
).
To get the current directory you need os.getcwd()
.
I don't get what's the problem in specifying the directory to operate in. It could be done with command line parameters (look at sys.argv
).
Upvotes: 0
Reputation: 3974
You are assigning the path you want to the variable 'Here', but then you are creating an empty string variable 'directory' and using that to provide the listing. Your listing will only contain files within your base folder (where you code is) because your are only searching for files in directory "". I think what you intend is to use 'Here' to do your listing
directory = Here
Upvotes: 0
Reputation: 1121982
Yes, it is wrong; you'll need to accept a argument that tells your script where to find the CSV files:
import argparse
def import_function(sourcedir):
for filename in os.listdir(sourcedir):
csvfilename = os.path.join(sourcedir, filename)
with open(csvfilename) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
# etc.
if __name__ == '__main__':
parser = argparse.ArgumentParser('CSV importer')
parser.add_argument('sourcedir', default='.')
options = parser.parse_args()
import_function(options.sourcedir)
Now your script accepts one command-line argument, a path to the directory to list your files in:
python yourscript.py /path/to/directory
The default is to look in the current directory still.
Upvotes: 0
Reputation: 113988
just set directory="/path/to/fldr/with/csv"
and full_name = os.path.join(directory,files)
Upvotes: 1