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.

2 Answers2

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.

Javier A
  • 539
  • 2
  • 12
  • 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 – Shoaib Naseer Apr 27 '21 at 05:59
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