Reputation: 11
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.
Upvotes: 1
Views: 1013
Reputation: 11
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
Upvotes: 0
Reputation: 569
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.
Upvotes: 2