The usual module is OS, Os.path and Shutil, so introduce them first.
python traversing folders and files
This is perhaps the most commonly used feature, as follows:
The code is as follows:
Import OS
Import Os.path
RootDir = "D:\\programmer\\training"
For the 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)
Explanatory notes:
1.os.walk returns a ternary group. Where Dirnames is the name of all the folders (without the path), filenames is the name of all the files (not including the path). The parent represents the parents directory.
2.case1 shows how to traverse all the directories.
3.case2 demonstrates how to traverse all the files.
4.os.path.join (Dirname,filename): Turns the form "/a/b/c" and "D.java" into/a/b/c/d.java ".
perl split path and file name
There are three common functions: separating the path to find the file name. Find the drive letter (Windows system) and find out the file extension.
The code is 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
Each of these three functions returns a two-tuple.
1.case1 separating directories and filenames
2.CASE2 Separator Letter and file name
3.case3 Delimited files and extensions