write mode in python not creating new file

Viewed 116
  • I was executing a program for creating a folder consisting multiplication table of 2 to 20, and for that, I am opening files of a folder that don't exist, and I am opening that with write mode, which ideally should create those folders and files if it doesn't exist but its giving error: FileNotFoundError: [Errno 2] No such file or directory: 'tables/mul_2.txt'
  • Program:
   #multiplication folder
for i in range(2,21):
   with open(f"tables/mul_{i}.txt", 'w') as f:
       for j in range(1,11):
           f.write(f"{i}X{j}={i*j}")
  • Python version: 3.8.5
1 Answers

In Python, the directories won't be automatically created for you if they don't already exist. You need to write additional code to actually create the directories. The code looks like this:

    import os

    ...

    # Create output directories if neccessary.
    os.makedirs(os.path.dirname('tables/mul_2.txt'), exist_ok=True)
Related