How To Step Through System Files With Python

How To Step Through System Files With Python

THE PYTHON OS.WALK() FUNCTION

Hi, welcome to my blog where I write about interesting Python stuff, this article is centered around the os.walk() function.

WHAT IS OS.WALK() FUNCTION?

Before I get to the formal description of what this is,

Pile of cartons with books inside

Imagine you have a pile of books in different boxes, unpacking the books to see the contents is a hell of a strenuous task and you wouldn't want to go that route. The stated scenario is similar to the files and directories of your computer.

path.gif

Let's say you want to check the contents of a folder that in itself has one or more sub-folders, checking the files would be time-consuming and strainous just like with the books. This is where the python os.walk() function serves as a life-saver.

The os.walk() function walks through a folder and its subfolders their file contents and displays their contents. It accepts one argument, which is the path of the folders and files to be iterated.

HOW CAN I USE THIS THEN?

Just like the python range() function that loops through a range of numbers, the os.walk() function also iterated through a specified path returns 3 values:

  • A string of the current folder's name.

  • A list of strings of the folders in the current folder.

  • A list of strings of the files in the current folders.

Let's get our hands to work.

jjj.gif

Enter this into your interactive shell:

myPath = '/home/udoka/Desktop'        #replace this with a path in your system
#iterating through the folders and files in myPath
for folderName, subfolder, fileName in os.walk(myPath):
     print('the current folder is' + folderName)
     print(subfolder)        #this returns a list of all subfolders
     print(fileName)         #this returns a list of all files
     for aSubFolder in subfolder:
         print('the current subfolder =' + aSubFolder)
     for eachFile in fileName:
         print('the file inside is =' + folderName + eachFile)
     print('\n')

WHAT NEXT???

Now, you can combine this function, with other functions in the shutil and os modules, to create new files, move, archive and rename files.

Thanks for reading, do leave a reaction to this. You can reach out to me on Twitter

hhhh.jpeg