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.
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
please do this
names = [filename1,filename2,.............]
index = names.index(filename you want to search)
print index
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
do like this
os.listdir(path).index('filename')
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.
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
please do this
names = [filename1,filename2,.............]
index = names.index(filename you want to search)
print index
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
do like this
os.listdir(path).index('filename')