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 directory, so that the created files will be put in that directory.
I tried this:
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)
But it doesn't give me what I wanted. It seems that the second line is not working as I wanted. Can anybody help me to solve the problem?
Use the os. chdir() function to change the current working directory to a new one. Use the os. mkdir() function to make a new directory.
Use the mkdir command to create one or more directories specified by the Directory parameter. Each new directory contains the standard entries dot (.) and dot dot (..). You can specify the permissions for the new directories with the -m Mode flag.
Python's OS module provides an another function to create a directories i.e. os. makedirs(name) will create the directory on given path, also if any intermediate-level directory don't exists then it will create that too. Its just like mkdir -p command in linux.
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.
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'
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With