0

Is there a way to create a file and automatically create its path?

for example:

with open("./path/to/file/data.txt", "w") as f:
    f.write("hello")

I want it to create the path ./path/to/file and then create the file data.txt and open it. instead it will give the error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: './path/to/file/data.txt'

I don't want to have to manually create the path one folder at a time.

2 Answers 2

1
import os

os.makedirs(os.path.dirname(fullPath))
Sign up to request clarification or add additional context in comments.

Comments

0

To know or get a file location or path, you first of all create a file module, on creating the file name module, python already knows its path. To create a module name use

               import os
             
               os.mkdir('data.txt')

You can use the code below to know or display the file module path displayed in your output shell.

               import os

               result = os.getcwd()

You can then further to create the file using

               with open('data2.txt', 'w') as f:
               f.write('You are good')

I added 2 to the file name i.e 'data2.txt' because python does not permit same name for file module as file name in the same directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.