The commonly used module is the OS, Os.path and Shutil, so introduce them first.
python traverses folders and files
This is probably the most commonly used feature, as follows:
Copy Code code as follows:
Import OS
Import Os.path
RootDir = "D:\\programmer\\training"
For parent, Dirnames, filenames in Os.walk (RootDir):
#case 1:
For dirname in Dirnames:
Print "Parent is:" + Parent
Print "DirName is:" + dirname
#case 2
For filename in filenames:
Print "Parent is:" + Parent
print "FileName with full path:" + os.path.join (parent, filename)
EXPLANATION Note:
1.os.walk returns a ternary group. Where Dirnames is the name of all folders (without paths), filenames is the name of all files (without paths). Parent represents the parents directory.
2.case1 demonstrates how to traverse all directories.
3.case2 demonstrates how to traverse all the files.
4.os.path.join (Dirname,filename): will be shaped like "/a/b/c" and "D.java" into/a/b/c/d.java.
perl split path and filename
There are three common functions: separating the path and finding the filename. Find the letter (Windows System) and find the file extension.
Copy Code code as follows:
Import Os.path
Spath= "D:/download/flight/flighthtml.txt"
# case 1:
P,f=os.path.split (spath);
Print "DIR is:" +p
print ' file is: ' +f
# case 2:
Drv,left=os.path.splitdrive (spath);
Print "Driver is:" +drv
Print "Left is:" +left
# Case 3:
F,ext=os.path.splitext (spath);
Print "F is:" +f
Print "ext is:" +ext
All three functions return a two-tuple.
1.case1 Delimited directory and filename
2.CASE2 Separator Letter and filename
3.case3 Delimited files and extensions