Save pandas csv to sub-directory

江枫思渺然 提交于 2019-12-01 20:02:08

问题


I am trying to save the output of the following code to a subdirectory:

for gp in g:
    filename = gp[0] + '.csv'
    print(filename)
    gp[1].to_csv(filename)

I have created the subdirectory first:

os.makedirs('MonthlyDataSplit')

But I can't find any information as to how to use to_csv to save to a subdirectory rather than the current directory. One approach I was thinking was to use the with "MonthlyDataSplit" open as directory but I can only find the equivalent for opening a file in a subdirectory.


回答1:


Basically you can build a path including subdirectories and pass this as the path arg to to_csv:

root = 'MonthlyDataSplit'
for gp in g:
    filename = gp[0] + '.csv'
    print(filename)
    gp[1].to_csv(root + '/' + filename)

You need to add slash separators to indicator what is a directory name and what is a filename, I would propose using os.path.join to simplify this process:

In [3]:
import os
root = 'MonthlyDataSplit'
os.path.join(root, 'some_file.csv')

Out[3]:
'MonthlyDataSplit\\some_file.csv'

For further subdirectories you can just add a new level:

In [8]:
import os
root = 'MonthlyDataSplit'
day = 'Day'
subdir = os.path.join(root, day)
final_path = os.path.join(subdir, 'some_file_name')
final_path

Out[8]:
'MonthlyDataSplit\\Day\\some_file_name'


来源:https://stackoverflow.com/questions/35892452/save-pandas-csv-to-sub-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!