1

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.

amin
  • 1,293
  • 13
  • 24
Deep
  • 83
  • 2
  • 7

3 Answers3

0

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
Avijit Dasgupta
  • 1,985
  • 3
  • 18
  • 36
0

please do this

names = [filename1,filename2,.............]
index = names.index(filename you want to search) 
print index
Afsal Salim
  • 468
  • 2
  • 14
0

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
Thomas Schultz
  • 2,342
  • 3
  • 24
  • 34