Search code examples
pythonpathexport-to-csvos.path

Save a CSV in same directory as python file, using 'to_csv' and 'os.path'?


I want this line to save the csv in my current directory alongside my python file:

df.to_csv(./"test.csv")

My python file is in "C:\Users\Micheal\Desktop\VisualStudioCodes\Q1"

Unfortunately it saves it in "C:\Users\Micheal" instead.

I have tried import os path to use os.curdir but i get nothing but errors with that.

Is there even a way to save the csv alongside the python file using os.curdir?

Or is there a simpler way to just do this in python without importing anything?


Solution

  • import os
    
    
    directory_of_python_script = os.path.dirname(os.path.abspath(__file__))
    
    df.to_csv(os.path.join(directory_of_python_script, "test.csv"))
    

    And if you want to read same .csv file later,

    pandas.read_csv(os.path.join(directory_of_python_script, "test.csv"))
    

    Here, __file__ gives the relative location(path) of the python script being runned. We get the absolute path by os.path.abspath() and then convert it to the name of the parent directory.

    os.path.join() joins two paths together considering the operating system defaults for path seperators, '\' for Windows and '/' for Linux, for example.

    This kind of an approach should work, I haven't tried, if does not work, let me know.