Blabber Blabber - 3 months ago 9
Python Question

Save .csv file in the same directory as .py file

I am tring to save my .csv file which is a result of some queries in the same location as the .py file.

import os
with open(os.path.dirname(os.path.abspath(__file__))+'MyCSVFile.csv','wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(myList)


I always seem to get my csv file one directory before. When I print os.path.dirname(os.path.abspath(__file__)) it gives me the proper path but the output MyCSVFile is saved one above. What is the problem here?

Answer

You have to use os.path.join to save the csv file in the same directory

import os

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'MyCSVFile.csv')

with open(csvfilename, 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(myList)

This should work as excepted

Comments