Home > Mobile >  Saving dataframes to .csv and create folder without specifying the file path
Saving dataframes to .csv and create folder without specifying the file path

Time:09-17

I am trying to find a way to save a few dataframes to .csv format as part of a ML routine I am designing in Python. Since this is composed of multiple steps, I would like to create folders in which to save dataframes as part of the code. Since the pandas.DataFrame.to_csv does not allow you to create folders, I have found this solution using os:

import os

import pandas as pd
    
outname = 'name.csv'
    
outdir = './dir'
if not os.path.exists(outdir):
    os.mkdir(outdir)
    
fullname = os.path.join(outdir, outname)    
    
df.to_csv(fullname)

However, this method requires you to specify the directory path. Since I would like the code to run on multiple devices without the need to rewrite the specific outdir each time, I am looking for a way to create a folder within the current Python working directory (whichever that may be on each device) in which to save the .csv file without the need to write down the path.

CodePudding user response:

You don't have to specify the full path, just the relative path.

Try:

import os
import pandas as pd
outname = 'name.csv'

outdir = 'dir'
if not os.path.exists(outdir):
    os.mkdir(outdir)
    
df.to_csv(f"{outdir}/{outname}")

Alternatively, you can use the __file__ variable that contains the full path to the script. __file__ will only work when you run it as a script and not in an interpreter.

import os
import pandas as pd
outname = 'name.csv'

outdir = 'dir'
fullname = os.path.join(os.path.dirname(__file__), outdir)
if not os.path.exists(fullname):
    os.mkdir(fullname)
    
df.to_csv(f"{fullname}/{outname}")
  • Related