maurobio
maurobio

Reputation: 1587

Finding files in a list by partial name in Python

I have a list of full file paths:

filelist = [
    "C:\Folder1\Files\fileabc.txt",
    "C:\Folder1\Files\filedef.txt",
    "C:\Folder2\Data\file123.txt"
]

I want to find a file in the list by its basename, with the extension, but without specifying full path.

I've tried something like this:

name = "filedef.txt"

if name in filelist:
   print "Found"

But it doesn't work.

Any hints?

Upvotes: 0

Views: 339

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30473

You need to do two things. First, iterate through the array. Second, escape \ special character.

paths = [r'C:\Folder1\Files\fileabc.txt', r'C:\Folder1\Files\filedef.txt', r'C:\Folder2\Data\file123.txt']

name = 'filedef.txt'

for path in paths:
   if name in path:
       print('Found', path)

Upvotes: 1

Related Questions