Python in Os.path module for manipulating files or folders
Os.path.exists (path) to determine if the file path exists
dir = "C:\Windows"
If Os.path.exists (dir):
print "DIR exists"
else:
Print "No exists"
Os.path.isfile (path) determines if path is a file
dir = "C:\windows\system32\cmd.exe"
If Os.path.isfile (dir):
Print "File exists"
else:
Print "No exists"
Os.path.getsize (path) Gets the size of the path file
Size = Os.path.getsize (dir)
Print size/1024
Os.path.walk (path) traverses path, returning a ternary group (Dirpath, Dirnames, filenames). Dirpath represents the path that is traversed, Dirnames represents a subdirectory name under that path, is a list, Filesnames represents the file name under that path, and is also a list. For example: When traversing to C:\Windows, Dirpath= "C:\Windows", Dirnames is a list of all the subdirectory names under this path, Dirnames is a list of all the filenames under this path
For (root, dirs, files) in Os.walk ("C:\windows"): Lists all files and filenames under the Windows directory
For filename in Files:
Print Os.path.join (root,filename)
For DIRC in dirs:
Print Os.path.join (ROOT,DIRC)
Question 1 Gets the size of the given folder?
To traverse the size of a file, simply traverse through all the files in the file and add up the size of all the folders
def getdirszie (dir):
for (Root,dirs,files) in Os.walk (Dir,false):
Size = 0
For filename in Files:
Size + = Os.path.getsize (Os.path.join (root,filename))
Print root,size/1024
Question 2 times a subdirectory of a folder, not traversing subdirectories of the word directory?
The Os.listdir (path) function lists the files and folders under the specified directory
dir = ' c:/windows '
If Os.path.exists (dir):
dirs = Os.listdir (dir)
For DIRC in dirs:
Print Dirc
else:
Print "Dir NOT exists"
Python Implements folder traversal