MrHat
MrHat

Reputation: 123

Most efficient way for searching all files with the same filename in python

I want to find the extensions for all files with the same name in a folder. So for example, if a directory contains 2 files named test.csv and test.txt. I want the program to return a list containing ".txt" and ".csv".

I have used:

glob.glob(file_name + '*') 

which works but is quite slow (0.03 seconds) when the folder contains many files. Is there some faster way of doing this in python?

Upvotes: 2

Views: 1409

Answers (2)

LinPy
LinPy

Reputation: 18578

try something like :

import re
import os

files = os.listdir(".")

my_files = re.findall(r"(\w+\.php)", " ".join(files))

print(my_files)

Upvotes: 1

Ahmed Hawary
Ahmed Hawary

Reputation: 471

You can use a dictionary with file names as keys and extensions as values as follow:

import os
data = {}
for file in os.listdir():
    name, ext = file.split('.')
    if name not in data.keys():
        data[name ] = list()

    temp = data[name].copy()
    temp.append(ext)
    data[name] = temp

print(data)

Upvotes: 0

Related Questions