python - Pandas DataFrame.to_csv 引发 IOError : No such file or directory

标签 python python-2.7 pandas

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

filename = './dir/name.csv'

df.to_csv(filename)

但是我得到了错误:

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

如果文件不存在,to_csv 方法是否应该能够创建文件?这就是我打算让它做的事情。

最佳答案

to_csv 如您所说,如果文件不存在,则确实会创建该文件,但不会创建不存在的目录。确保首先创建了您尝试保存文件的子目录。

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

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)

如果您需要经常这样做,这可以很容易地封装在一个函数中。

关于python - Pandas DataFrame.to_csv 引发 IOError : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47143836/

相关文章:

python - 使用 Python 读取带有日期对象和 float 的逗号分隔文件

python - 尝试使用 Keras 进行预测时返回 nan

Python Numpy intersect1d 一维数组与二维数组

python - 使用牛津项目的情感 API

pandas - IPython 笔记本 : What is the default encoding?

pandas - 巨大的稀疏数据帧到 scipy 稀疏矩阵,无需密集变换

python - 如何在没有输入的情况下使用 raw_input

python - 创建递归函数来查找具有特定属性值的对象

python-2.7 - Python-网络x : Neighbours with certain weight

python - pandas 中数据的清理