0

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?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
maurobio
  • 1,480
  • 4
  • 27
  • 38

1 Answers1

1

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)
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Couldn't figure out how to escape the '\' for the path in the path list. A similar question has been presented here: https://stackoverflow.com/questions/21605526/how-to-create-raw-string-from-string-variable-in-python but the answers were not quite helpful for me. – maurobio Aug 27 '17 at 22:53
  • I did understand, but my problem is that I get the names in the file list from a GUI interface and populate the list as follows: filelist.append(str(filename)), where filename is returned from a standard file dialog. Cannot figure out how to escape the backlashes in the name in that case. – maurobio Aug 27 '17 at 22:59