In the Linux system to traverse the file is not a fresh function, if given a directory, according to the structure of the directory to do some operations, this is going to traverse, talk about traversal can not say recursion, because traversal is a typical application of recursive scenario, that what is recursion? In fact, recursion is the definition of the function called itself, such as listing all the files in the specified directory, if the directory in addition to files and directories, you need to enter this subdirectory, and so on until there is no directory of the end, recursive more abstract, we directly illustrate the example:
#!/usr/mport OS
Import OS
def Rec (path):
All_files = Os.listdir (path)
For file in All_files:
PF = Os.path.join (path,file)
If Os.path.isdir (PF):
Rec (PF)
Else
Print Os.path.join (PATH,PF)
Rec ('/root/script ')
This is a simple example, if the variable pf is a directory, then call the REC function, if not directly print out the contents of the directory and files.
If the above example is more difficult to understand, then everyone should not worry, who let me use the language of the great god of Python, because in Python has provided us with a os.walk () function to help us solve this more burning problem, this function to accept a directory, It then returns a ternary group Tupple (Dirpath, Dirnames, filenames), respectively, which says:
The root path, a list of subdirectories under the root path, and a list of all files under the root path.
So to traverse a directory file, and finally with Os.path.join (Dirpath, name). You can get the full path of the file, we have a practical example, such as I want to back up all the Conf files on 1 machines, we use the Os.walk () The function can traverse all of the system's conf files and copy them to the directory we specify, as follows:
Import OS, shutil, sys
If not Os.geteuid () ==0:
Sys.exit (0)
If not Os.path.isdir ("/backup"):
Os.mkdir ("/backup", 384)
For Root, dirs, the files in Os.walk ('/'):
For filename in Files:
If ". conf" in FileName:
Abspath = Os.path.join (root, filename)
Shutil.copy2 (Abspath, "/backup")
With this os.walk () function can help us to quickly traverse the specified folder content, so very useful in practice, we suggest to write a few more examples to understand its meaning, this article is here, welcome message exchange.