将 pandas csv 保存到子目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35892452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:50:13  来源:igfitidea点击:

Save pandas csv to sub-directory

pythoncsvpandasfilepath

提问by PaulBarr

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_csvto save to a subdirectory rather than the current directory. One approach I was thinking was to use the with "MonthlyDataSplit" open as directorybut I can only find the equivalent for opening a file in a subdirectory.

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

采纳答案by EdChum

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

基本上,您可以构建一个包含子目录的路径并将其作为路径 arg 传递给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.jointo simplify this process:

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

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'