1
    dirLocation = "Patients Data/PatientsTimelineLog.csv"

try:
    if os.path.isfile(dirLocation):
        print("Directory exist." + dirLocation)
    else:
        print("Directory does not exists. Creating new one." + dirLocation)
        os.makedirs(os.path.dirname(dirLocation))
except IOError:
    print("Unable to read config file and load properties.")

Automatically creating directories with file output

Want to create a PatientsTimelineLog.csv inside Patients Data folder in one go if it does not exist. The above link is creating the folder but the csv file is not made. makedir is used to make directory but i want inside the file in it like the path given above in dirLocation.

4
  • Look up pathlib Commented Apr 26, 2021 at 13:59
  • Using PurePath(dirLocation) get the name of csv file in the path. Can you guide how to make that file in new created folder Patients Data? os.makedirs(os.path.dirname(dirLocation)) Above live giving none in return otherwise join can be used to concatenate file and path Commented Apr 27, 2021 at 8:06
  • Having awareness of the path is vital. I'm not at my PC now but will give an example when I can. Commented Apr 27, 2021 at 9:18
  • ok waiting for guidence Commented Apr 27, 2021 at 9:47

2 Answers 2

2

Inside the else, you can directly use os.makedirs(dirLocation).

When you use os.path.dirname(dirLocation) you are selecting everything except the name of the csv file. That is why you are creating only the folder.

Sign up to request clarification or add additional context in comments.

1 Comment

It creates another folder inside Patient Data. But I want csv file made inside the folder. Patient Data folder containing this file PatientsTimelineLog.csv no the filder
0
try:
    folder_path = os.path.split(os.path.abspath(dirLocation))
    sub_path = folder_path[0]
    if os.path.isdir(sub_path):
        print("Directory exist: " + dirLocation)
    else:
        print("Directory does not exists. Creating new one: " + dirLocation)
        file_name = PurePath(dirLocation)
        obj = file_name.name
        filepath = os.path.join(sub_path, obj)
        os.makedirs(sub_path)
        f = open(filepath, "a")
except IOError:
    print("Unable to read config file and load properties.")

This is the answer to my question. pathlib did lot of help in this question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.