pandas DataFrame.to_csv提高IOError:没有这样的文件或目录 [英] Pandas DataFrame.to_csv raising IOError: No such file or directory

查看:922
本文介绍了 pandas DataFrame.to_csv提高IOError:没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好:我正在尝试使用Pandas DataFrame.to_csv方法将dataframe保存到csv文件:

Hi: I am trying to use the Pandas DataFrame.to_csv method to save a dataframe to a csv file:

filename = './dir/name.csv'

df.to_csv(filename)

但是我遇到了错误:

IOError: [Errno 2] No such file or directory: './dir/name.csv'

如果文件不存在,to_csv方法不能创建该文件吗?这就是我打算要做的.

Shouldn't the to_csv method be able to create the file if it doesn't exist? This is what I am intending for it to do.

推荐答案

to_csv确实会创建文件(如您所说的不存在),但不会创建不存在的目录.确保首先创建了要在其中保存文件的子目录.

to_csv does create the file if it doesn't exist as you said, but it does not create directories that don't exist. Ensure that the subdirectory you are trying to save your file within has been created first.

我在工作中经常做这样的事情:

I often do something like this in my work:

import os

outname = 'name.csv'

outdir = './dir'
if not os.path.exists(outdir):
    os.mkdir(outdir)

fullname = os.path.join(outdir, outname)    

df.to_csv(fullname)

如果您需要经常执行此操作,则可以轻松地将其包装在一个函数中.

This can easily be wrapped up in a function if you need to do this frequently.

这篇关于 pandas DataFrame.to_csv提高IOError:没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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