Data_Science_Learner
Data_Science_Learner

Reputation: 29

Find a file containg a string in its name using Python

I have a sheet in excel which contains the names of files. I have a folder which contains the files in jpg. The file names in the excel sheet are not complete file names but a part of the full name of the file. I have to search for the file name from the folder and seperate those matching files to a new folder. Please guide me how can i achieve this target.

Upvotes: 0

Views: 806

Answers (1)

abgup
abgup

Reputation: 56

You can search for part of the file name in a folder by looking through each element filename in the folder and see if string contains substring:

import os

directory = r'C:\Users\admin'
for filename in os.listdir(directory):
    if substring in filename:
        print(filename)

You didn't ask how to iterate through elements of an excel sheet, but this can be done via read csv file or a xlsx reader package in python and just put another loop outside the one above for each element. For every file, just store in a list rather than print.

Upvotes: 1

Related Questions