- Python

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.

>>> import os
>>> os.getcwd()
'/home/codesexplorer/Desktop'

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.

>>> os.listdir(os.getcwd())
['Codes','test.txt','Untitled1.py']

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.

>>> os.mkdir('Untitled_Directory')
>>> oslistdir(os.getcwd())
['Codes','Untitled_Directory','test.txt','Untitled1.py']

Renaming a Directory or File

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

>>> os.rename('Untitled_Directory','New_Name')
>>> oslistdir(os.getcwd())
['Codes','New_Name','test.txt','Untitled1.py']

Deleting a Directory or File

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

>>> os.rmdir('New_Name')
>>> os.remove('test.txt')
>>> oslistdir(os.getcwd())
['Codes','Untitled1.py']

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

import os
arr = []
OUTPUT = "/home/codesexplorer/Desktop"
for i in os.listdir(OUTPUT):
        if (i.find("raw") != -1):
            arr.append(i)

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.

import os
arr = []
OUTPUT = "/home/codesexplorer/Desktop"
for i in os.listdir(OUTPUT):
    if i.endswith(".JPG"):
        if (i.find("raw") != -1):
            arr.append(i)

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.

Leave a Reply