简体   繁体   中英

Python create path with file

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.

import os

os.makedirs(os.path.dirname(fullPath))

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 ie 'data2.txt' because python does not permit same name for file module as file name in the same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM