2

I have a Python 3 test.py script where some data is created which I want to save to a file with a user-defined name, say data.csv. The folder in which this script is sitting has a /Results folder inside it. What I want to do is to create a subfolder inside Results with the name of the current script and store my file inside it. So, what I want is my file to be stored in ./Results/test/data.csv. I want these folders to be created if they don't previously exist and if they do exist, along with the file, I want data.csv to be replaced. I want this to work on any OS. How should this be done "pythonically"?

~/
  test.py
  Results/
     test/
        data.csv

Here's a test code where data.csv is not being saved where I want it. How should I edit it?

import pandas as pd

filename = "data.csv"
df = pd.DataFrame([1,2,3])
df.to_csv(filename)
Bella
  • 181
  • 2
  • 11

2 Answers2

1

You can use the os.path module to do a series of folder checking and make the folder if not exist. And then you can access the current filename by using the __file__ attribute.

import os.path
import pandas as pd

file_name = os.path.splitext(os.path.basename(os.path.realpath(__file__)))[0]

full_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Results")

if not os.path.exists(full_path):
    os.mkdir(full_path)

    if not os.path.exists(os.path.join(full_path, file_name)):
        os.mkdir(os.path.join(full_path, file_name))

file_location = os.path.join(full_path, file_name, 'data.csv')

df = pd.DataFrame([1, 2, 3])
df.to_csv(file_location)
abccd
  • 23,977
  • 10
  • 56
  • 68
0

I would use:

import platform
import os

if platform.system().lower() == 'windows':
    print("%s" % os.path.expandvars("%USERPROFILE%"))
elif platform.system().lower() == 'posix':
    print("%s" % os.path.expandvars("$PATH")) #or some other posix var like USER...
else:
    print("What the heck type of os is this?!?")

I think this may also be useful for you.

chevydog
  • 123
  • 7