In python how to change to a new directory if it does exist or even doesn't exist?
Assuming that the current working directory is '/home' (the python file is also stored there) and I wanna change it to a new directory like '/home/a'. What should I do if there are two possibilities that '/home/a' doesn't exist or does exist?
Here is my attempting code:
import os
current_path=os.path.dirname(os.path.abspath('t.py'))
print(current_path)
os.makedirs('/home/a')
os.chdir('/home/a')
print(os.path.dirname(os.path.abspath('t.py')))
And there is the error feedback of my code:
[user@sahara ~]$ python t.py
/home
Traceback (most recent call last):
File "t.py", line 4, in
os.makedirs('/home/a')
File "/usr/lib/python3.7/os.py", line 221, in makedirs
mkdir(name, mode)
FileExistsError: [Errno 17] File exists: '/home/a'