Search code examples
pythonpandaspathlib

Path is correct when printed to console, but not in pandas .to_csv method


Here's a frustrating one that I don't understand:

from pathlib import Path
DATA_DIR = "c:/my/dir/"
[...]
df.to_csv(Path(DATA_DIR).parent.joinpath(DATA_DIR, "c_bat.csv"))

This gives an error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\my\\dir\\c_bat.csv'

However, when I do this:

print(Path(DATA_DIR).parent.joinpath(DATA_DIR, "c_bat.csv"))

It prints fine:

C:\my\dir\c_bat.csv

Why does Print get it right, but df.to_csv get it so wrong, when it's ostensibly the exact same code?


Solution

  • The most practical way to deal with joining paths using pathlib is the "slash" operator, as in the following code:

    # Common name used in pathlib examples
    p = Path(DATA_DIR)
    [...]
    df.to_csv(p / "c_bat.csv"))