Reputation: 349
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?
Upvotes: 0
Views: 2568
Reputation: 134
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
Upvotes: 2
Reputation: 8290
Remove the call to os.path.dirname
since you are already calling os.path.abspath
. Calling dirname
returns the directory component thus you are getting the directory up in the hierarchy. BTW: use os.path.join
to join parts of a directory.
Upvotes: 1