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?

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Couldn't figure out how to escape the '\' for the path in the path list. A similar question has been presented here: stackoverflow.com/questions/21605526/… but the answers were not quite helpful for me.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.