Os.path.walk is a fruitful system command in python. Using walk we can easily parse recursively through the folder.It gives the file names with in the folder and in the sub folders. The syntax of walk is very simple. os.path.walk takes exactly three arguments. Syntax of os.path. walk is-
os.path.walk(parent_folder,function_call,pattern)
The first argument ‘parent_folder’ is the directory name that we need to parse. function_call is a function call that used to parse each folder and sub folder. It also takes three arguments. The third one pattern is actually a filtering parameter. We can give the extensions of file that we need to manipulate. If we need to get only mp3 files then we can give ‘*.mp3′ for pattern. Like we can give any extension. For getting all the files we can give ‘*.*’ for pattern.
Here am giving a small example to show the power of walk.
import sys import shutil import re from fnmatch import fnmatch import os, os.path global destntn_dir destntn_dir = None def mp3_finder(pattern, dir, files): for filename in files: if fnmatch(filename, pattern): file_path = os.path.join(dir, filename) #Copying files to destination folder shutil.copy(file_path,destntn_dir) def main(): ## Collect command line arguments parent_folder = sys.argv[1] global destntn_dir destntn_dir = sys.argv[2] #Creating Destination Folder os.mkdir(destntn_dir) ## Walk folder os.path.walk(parent_folder,mp3_finder, '*.mp3') if __name__=="__main__": main()
The above example copy all the mp3 files from the given folder and its sub folders to another folder. Here we are creating the destination folder inside the program.
Usage:
Run the program in the console using python command. We can give the source folder and destination folder as command line arguments. Please give the folder names along with their paths. Here the destination folder will create according to the path.
Run the program in the console using python command. We can give the source folder and destination folder as command line arguments. Please give the folder names along with their paths. Here the destination folder will create according to the path.
No comments:
Post a Comment