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

PythonPython 2.7Pandas

Python Problem Overview


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)

However I am getting the error:

IOError: [Errno 2] No such file or directory: './dir/name.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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

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

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=True will also create any necessary parent directories, and exist_ok=True means it won't raise an error if the directory already exists, so you don't have to explicitly check that separately.

Solution 3 - Python

I had this error when I accidentally added file:// at the begging of the save path. Since search brought me here, might be also helpful to someone.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoLaView Question on Stackoverflow
Solution 1 - PythonqRTPCRView Answer on Stackoverflow
Solution 2 - PythonTimView Answer on Stackoverflow
Solution 3 - PythonKobyView Answer on Stackoverflow