When writing cache is used, it is often encountered to build multiple layers of directory operations, which we manually to operate too cumbersome, today we have a look at the use of Python recursion to build a multi-level directory method:
First on the code:
#! /usr/bin/env python
#coding =utf-8
import OS
def mkfolder (path):
if not os.access (Path,os. R_OK):
#print 1212
#print os.path.dirname (path)
path_last = len (path)-1
if path[path_last] = = '/' or Path[path_last] = = = ' \ ':
path = Path[0:path_last]
mkfolder (os.path.dirname (path))
if not Os.path.isfile (path):
os.mkdir (path,0755)
mkfolder ('./google/baidu/yahoo/sougou/')
Of course we can also use the Mkdirs () function (Note: PHP does not have this function OH). Thanks for the first floor reminder ~ ~
But with these two functions, we have a similarity of Python and PHP functions ~ ~
This is the way to use recursion to build a multi-tiered directory, and here's an explanation:
Line eighth: Detect whether the directory is readable, that is, to detect whether the directory exists
第13-15: This is a place to pay special attention to, because if you don't remove the last "/" of the path, it will cause a dead loop, specifically because: os.path.dirname (path) will eventually become "", and then the cycle continues, resulting in a dead loop
Finally detect if it is a file, if not, create a directory
That's the Python way, so let's look at how PHP does it (you'll see that Python and PHP are surprisingly similar after reading)
Code on:
function Mkfolder ($path) {
if (!is_readable ($path)) {
Mkfolder (dirname ($path));
if (!is_file ($path)) {
mkdir ($path, 0777);
}
}
}
Did you see it? The recursive setting of the two languages is so similar to the hierarchical directory functions
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/