Python: List all Files in Directory and Find a string in file name

In this article, you’ll learn about creating a directory, renaming it, list all files in a directory and find if a string is there is in file name.

What is Directory?

A directory or folder is a collection of files and sub-directories. Python has the os module, which provides a portable way of using operating system dependent functionality.

Get current Working Directory

We can get the present working directory using the os.getcwd() command. The command returns the path of the current working directory in the form of a string.

List all Directories and Files

All the files and sub directories present inside a directory can be known using os.listdir( ) command. This command takes the path and returns all the sub directories and files present the current working directory.

Making a New Directory

mkdir() method of Python is used to create a New Directory. This command takes in the path of the new directory, if not specified new directory is created in current working directory.

Renaming a Directory or File

The os.rename(‘old_name’,’new_name’) method will rename the directory or file.

Deleting a Directory or File

The os.rmdir() method will delete the directory and os.remove() deletes the file with file name specified.

Finding a string in the File Name

We will go through small Python program that lists all files from a directory and finds if a string “raw” is present. If YES then appends a array to list all file name that have “raw”. So here it is

This can be extended like all image file that contains string “raw” in the file name to be listed. The image file ending with *.jpg is considered here. You can choose the format accordingly. So code for it is here.

There are other file processing techniques in Python, We will discuss them in upcoming posts. Till then, you can have a look at some of our Machine Learning Posts.

Abhay Kagalkar
Software developer, Blogger, Learner,...