How to read filenames in a folder and access them in an alphabetical and increasing number order?
filenames, glob, list, python
Solution
from glob import glob
import os
files_list = glob(os.path.join(my_folder, '*.dat'))
for a_file in sorted(files_list):
# do whatever with the file
# 'open' or 'with' statements depending on your python version
Problem
I would like to ask how to efficiently handle accessing of filenames in a folder in the right order (alphabetical and increasing in number). For example, I have the following files in a folder: apple1.dat, apple2.dat, apple10.dat, banana1.dat, banana2.dat, banana10.dat. I would like to read the contents of the files such that apple1.dat will be read first and banana10.dat will be read last. Thanks. This is what I did so far. ``` from glob import glob files=glob('*.dat') for list in files # I read the files here in order ``` But as pointed out, apple10.dat comes before apple2.dat