将pandas csv保存到子目录 [英] Save pandas csv to sub-directory

查看:77
本文介绍了将pandas csv保存到子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下代码的输出保存到子目录中:

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)

我首先创建了子目录:

os.makedirs('MonthlyDataSplit')

但是我找不到任何有关如何使用to_csv保存到子目录而不是当前目录的信息.我当时想的一种方法是使用with "MonthlyDataSplit" open as directory,但我只能在子目录中找到等效的打开文件的方法.

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.

推荐答案

基本上,您可以构建一个包含子目录的路径,并将其作为路径arg传递给to_csv:

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)

您需要添加斜杠分隔符以指示什么是目录名和什么是文件名,我建议使用os.path.join来简化此过程:

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'

这篇关于将pandas csv保存到子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆