0

I am having this code where I am reading all the JSON files stored:

json_files = glob.glob('testproject/JSON/*.json', recursive=True)
print(json_files)

Now I am creating a UML diagram for which I am creating a new file and giving the same name as the JSON file which is loaded without the .json extension.

I have this code doing that for me:

    for single_file in json_files:
      with open(single_file, 'r') as f:
        json_data = json.load(f)
      name = single_file.split('.')

      # From JSON, create GANTT Diagram
      with open(name[0].split('/')[-1] + ".uml", "w") as f:
        #some logic inside this part

When I run the code it gives me this error:

    ['testproject/JSON\\abc.json', 'testproject/JSON\\xyz.json']
    Traceback (most recent call last):
      File "c:\Project\testproject\extract.py", line 28, in <module>
        with open(name[0].split('/')[-1] + ".uml", "w") as f:
    FileNotFoundError: [Errno 2] No such file or directory: 'JSON\\abc.uml'

as it can been seen that when i print the json_files variable the path is something like this testproject/JSON\abc.json and because of that the split is not working properly maybe. Can someone guide me here? Thanks in advance.

matszwecja
  • 6,357
  • 2
  • 10
  • 17
Zykxpython
  • 15
  • 2
  • 1
    It's usually better/easier to use proper path libraries like `os.path` or `pathlib` than to try to do string manipulation. If I understand correctly you want the filename? You can do `from pathlib import Path; Path(name[0]).stem` to get that – Robin De Schepper Sep 19 '22 at 09:16
  • 1
    Also [How do I get the filename without the extension from a path in Python?](https://stackoverflow.com/q/678236/4046632) – buran Sep 19 '22 at 09:18
  • @RobinDeSchepper yes your idea worked. Thanks – Zykxpython Sep 19 '22 at 09:22

1 Answers1

0

This worked

from pathlib import Path 


for single_file in json_files:
  with open(single_file, 'r') as f:
    json_data = json.load(f)
  name = single_file.split('.')

  # From JSON, create GANTT Diagram
  with open(Path(name[0]).stem + ".uml", "w") as f:
    #some logic inside this part
Zykxpython
  • 15
  • 2