Search code examples
pythonpython-3.xglob

How to get a file name inside a particular folder and pass that file name into a for loop index?


I have a folder named test ,which contains 11.txt,12.txt,13.txt

I need to read the content of the test folder , find the largest text file name and pass it into for loop starting index :

def find_largest_index(file_path):
  txt_files = glob.glob("*.*")
  #do smthing here to find the largest filename index 

file_path = 'home/Documents/PythonCodeIsHere/test'
i = find_largest_index(file_path)
for page_i in pages_num[i-1:]:
    print(page_i)

Solution

  • import os
    
    filenames = [int(filename[:-4]) for filename in os.listdir(file_path) if ( filename.endswith('.txt') and not filename.startswith('running') )]
    i = max(filenames)