I am working on a project where I have to edit a few lines of content in some 400 different files. They are all in the same folder, and have each got unique names. For the sake of this question, I will call them fileName001.conf
to fileName420.conf
.
I am using a python script to obtain the contents of each file before going on to make the edits programmatically. At the moment, I am using this snippet to get the files with some print()
lines for debugging:
folderPath = '/file/path/to/list/of/conf/files'
for filename in os.listdir(folderPath):
print('filename = ' + filename)
print('filepath = ' + folderPath + '/' + filename)
with open(folderPath + '/' + filename, 'r') as currFile:
#... code goes on...
Lines 4 and 5 are designed for debugging only. Running this, I noticed that the script was exhibiting some strange behaviour - the order in which the file names are printed seemed to change on each run. I took this a step further and added the line:
print(os.listdir(folderPath))
Before the for loop in my first code snippet. Now when I run the script from terminal, I can confirm that the output that I get, while contains all file names, has a different order each time:
RafaGuillermo@virtualMachine:~$ python renamefiles.py
['fileName052.txt', 'fileName216.txt', 'fileName084.txt', 'fileName212.txt', 'fileName380.txt', 'fileName026.txt', 'fileName119.txt', etc...]
RafaGuillermo@virtualMachine:~$ python renamefiles.py
['fileName024.txt', 'fileName004.txt', 'fileName209.txt', 'fileName049.txt', 'fileName166.txt', 'fileName198.txt', 'fileName411.txt', etc...]
RafaGuillermo@virtualMachine:~$
As far as getting past this goes - as I want to make sure that I go through the files in the same order each time, I can use
list = sorted(os.listdir(folderPath))
Which alphebetises the list, though it seems counter-intuitive that os.listdir()
returns the list of filenames in a different order each time I run the script.
My question is therefore not how can I get a sorted list of files in a directory using os.listdir()
, but:
What method does os.listdir()
use to retrieve a list of files and why does it seemingly populate its return value in a different way on each call?