Not Able to Create Files and Directories From a Dictionary

Can you please take a look at this snippet and let me know why the text files (thisdict[key]) are not creating inside each directory (key)

I can create the directories but the text files are not generating!

import os

parent_dir = "B:/PyTest/"
thisdict =  {
  "1.1": "1.1-text.txt",
  "1.2": "1.1-text.txt",
  "1.3": "1.1-text.txt"
}

for key in thisdict:
  directory = key
  path = os.path.join(parent_dir, directory)
  if not os.path.exists(path):
      os.makedirs(path)
  f = open(thisdict[key], "w")
  f.write(thisdict[key])
  f.close()

Solution 1:

The error coming from the file path that using to create the file , you were not using the correct path

import os

parent_dir = "D:/PyTest/"
thisdict =  {
  "1.1": "1.1-text.txt",
  "1.2": "1.1-text.txt",
  "1.3": "1.1-text.txt"
}

for key in thisdict:
  directory = key
  path = os.path.join(parent_dir, directory)
  if not os.path.exists(path):
      os.makedirs(path)
  file_path = os.path.join(path,thisdict[key])
  f = open(file_path, "w")
  f.write(thisdict[key])
  f.close()

Solution 2:

You can use the pathlib library to make it easier.

from pathlib import Path

parent_dir = Path()
this_dict = {
    "1.1": "1.1-text.txt",
    "1.2": "1.1-text.txt",
    "1.3": "1.1-text.txt"
}

for key in this_dict:
    path = Path(parent_dir / key)
    path.mkdir(parents=True, exist_ok=True)
    with open(path / this_dict[key], 'w') as f:
        f.write(this_dict[key])