The difference between Python os. mkdir of and os. makedirs of
- 2021-10-11 19:04:10
- OfStack
os. makedir (path) and os. makedirs (path)
In today's work, the hadoop file is synchronized to the server disk. Because there are many file categories and directories, it is necessary to judge whether the file exists when migrating
There are two methods os. mkdir (path) and os. makedirs (path)
os.mkdir(path)
His function is to create directories at level 1 and level 1. The premise is that the previous directory already exists. If it does not exist, it will report an exception, which is troublesome, but it has its reasons. When your directory is dynamically created according to the file name, you will find that it is tedious but very secure, and it will not create a double-layer or multi-layer error path because of your 1-hour hand shaking and creation.
import os
os.mkdir('d:\hello') # Normal
os.mkdir('d:\hello\hi') # Normal
# If d:\hello Directory does not exist
# Then os.mkdir('d:\hello\hi') Execution failed
os.makedirs(path)
You can guess his difference from the writing alone. He can create a multi-level directory at a time. Even if the intermediate directory does not exist, it can be created normally (for you). It's terrible to think about it. You wrote a wrong word in the intermediate directory..........
import os
os.makedirs('d:\hello') # Normal
os.makedirs('d:\hello\hi') # Normal
# If d:\hello Directory does not exist
# Then os.makedirs('d:\hello\hi') # Still normal
Each has its own advantages and disadvantages, so choose to use it according to your own needs.
Supplement: Application of os. path and os. makedirs in Python (judging whether files or folders exist and creating folders)
import os
import numpy as np
data = np.array([1, 2, 3])
if not os.path.exists("./data/"):
print("# path not exists")
os.makedirs("./data/")
if not os.path.exists("./data/data.npy"):
print("# data.npy not exists")
np.save("./data/data.npy", data)
print("# path exists? :", os.path.exists("./data/"))
print("# data.npy exists? :", os.path.exists("./data/data.npy"))
Run results:
# path not exists
# data.npy not exists
# path exists? : True
# data.npy exists? : True