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,413
  • 14
  • 24
Deep
  • 83
  • 3
  • 7

4 Answers4

1

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
  • 2,055
  • 3
  • 22
  • 36
0

please do this

names = [filename1,filename2,.............]
index = names.index(filename you want to search) 
print index
Afsal Salim
  • 486
  • 3
  • 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,446
  • 3
  • 25
  • 36
0

do like this

  os.listdir(path).index('filename')
Omar Essam El-Din
  • 1,415
  • 14
  • 17