Skip to content Skip to sidebar Skip to footer

New Folder That Is Created Inside The Current Directory

I have a program in Python that during the processes it creates some files. I want the program to recognize the current directory and then then creates a folder inside the director

Solution 1:

think the problem is in r'/new_folder' and the slash (refers to the root directory) used in it.

Try it with:

current_directory = os.getcwd()
final_directory = os.path.join(current_directory, r'new_folder')
if not os.path.exists(final_directory):
   os.makedirs(final_directory)

That should work.


Solution 2:

One thing to note is that (per the os.path.join documentation) if an absolute path is provided as one of the arguments, the other elements are thrown away. For instance (on Linux):

In [1]: import os.path

In [2]: os.path.join('first_part', 'second_part')
Out[2]: 'first_part/second_part'

In [3]: os.path.join('first_part', r'/second_part')
Out[3]: '/second_part'

And on Windows:

>>> import os.path
>>> os.path.join('first_part', 'second_part')
'first_part\\second_part'
>>> os.path.join('first_part', '/second_part')
'/second_part'

Since you include a leading / in your join argument, it is being interpreted as an absolute path and therefore ignoring the rest. Therefore you should remove the / from the beginning of the second argument in order to have the join perform as expected. The reason you don't have to include the / is because os.path.join implicitly uses os.sep, ensuring that the proper separator is used (note the difference in the output above for os.path.join('first_part', 'second_part').


Post a Comment for "New Folder That Is Created Inside The Current Directory"