Python Pandas DataFrame.to_csv 引发 IOError:没有这样的文件或目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47143836/
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-08-19 18:01:53  来源:igfitidea点击:

Pandas DataFrame.to_csv raising IOError: No such file or directory

pythonpython-2.7pandas

提问by LoLa

Hi: I am trying to use the PandasDataFrame.to_csvmethod to save a dataframeto a csvfile:

嗨:我正在尝试使用该PandasDataFrame.to_csv方法将 a 保存dataframecsv文件:

filename = './dir/name.csv'

df.to_csv(filename)

However I am getting the error:

但是我收到错误:

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

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

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

回答by qRTPCR

to_csvdoes 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.

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

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.

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

回答by Tim

Here is an alternative way to do this using the excellent standard library pathlibmodule, which generally makes things neater.

这是使用出色的标准库pathlib模块执行此操作的另一种方法,它通常使事情变得更整洁。

As explained elsewhere, to_csvwill create the fileif it doesn't exist, but won'tcreate any non-existent directories in the path to the file, so you need to first ensure that these exist.

如别处所述,如果文件不存在,to_csv将创建该文件,但不会在文件路径中创建任何不存在的目录,因此您需要首先确保这些目录存在。

from pathlib import Path

output_file = 'my_file.csv'
output_dir = Path('long_path/to/my_dir')

output_dir.mkdir(parents=True, exist_ok=True)

df.to_csv(output_dir / output_file)  # can join path elements with / operator

Setting parents=Truewill also create any necessary parent directories, and exist_ok=Truemeans it won't raise an error if the directory already exists, so you don't have to explicitly check that separately.

设置parents=True还将创建任何必要的父目录,exist_ok=True这意味着如果目录已经存在,则不会引发错误,因此您不必单独明确检查。