How to find the position/index of a particular file in a directory?

Question:

I am new to python.I have a list of file names contained in a folder and I want to build a function which can search and return the position of a particular file in the list of files.

Asked By: Deep

||

Answers:

Suppose, you have a list of string list_of_names=["Abc","Def","Ghi","Jkl"].

You can use list.index() method to find the index of a particular string as given below:

>> list_of_names.index("Abc")
>> 0
>> list_of_names.index("Jkl")
>> 3
Answered By: Avijit Dasgupta

please do this

names = [filename1,filename2,.............]
index = names.index(filename you want to search) 
print index
Answered By: Afsal Salim

Something like this would work. Assuming you wanted the files alphabetical.

>>> from os import listdir
>>> my_files = listdir('./')
>>> my_files.sort()
>>> my_files.index('myfile.txt')
9
Answered By: Thomas Schultz

do like this

  os.listdir(path).index('filename')
Answered By: Omar Essam
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.