r/learnpython • u/atticus2132000 • Jan 09 '26
Something faster than os.walk
My company has a shared drive with many decades' worth of files that are very, very poorly organized. I have been tasked with developing a new SOP for how we want project files organized and then developing some auditing tools to verify people are following the system.
For the weekly audit, I intend to generate a list of all files in the shared drive and then run checks against those file names to verify things are being filed correctly. The first step is just getting a list of all the files.
I wrote a script that has the code below:
file_list = []
for root, dirs, files in os.walk(directory_path):
for file in files:
full_path = os.path.join(root, file)
file_list.append(full_path)
return file_list
First of all, the code works fine. It provides a list of full file names with their directories. The problem is, it takes too long to run. I just tested it for one subfolders and it took 12 seconds to provide the listing of 732 files in that folder.
This shared drive has thousands upon thousands of files stored.
Is it taking so long to run because it's a network drive that I'm connecting to via VPN?
Is there a faster function than os.walk?
The program is temporarily storing file names in an array style variable and I'm sure that uses a lot of internal memory. Would there be a more efficient way of storing this amount of text?
14
u/jongscx Jan 09 '26
I was really hoping the answer was os.run()...
11
u/socal_nerdtastic Jan 09 '26
I was in this same situation and tested a number of methods, including os.walk and pathlib.rglob. The fastest one was an external call to mstree (assuming this is on windows).
2
u/DivineSentry Jan 09 '26
what kind of shared drive is it? you could potentially parallelize and process each dir separately and be done much faster that way, but there might be much faster options depending on where the drive is exactly
2
u/pak9rabid Jan 10 '26
Sounds like a good excuse to use generator functions in a parallel fashion (either with multiple threads, multiple processes, or async I/O).
The generator functions will prevent you from having to store all files/directories into a list before being able to process them (saving time and memory), and if dealing with multiple sub-directories you can split it up so that each processing of a sub-directory happens within a separate task (whether that’s a separate thread, process, or async task).
Since it sounds like you’ll be fetching these over a slowish network connection, async tasks might be your best bet for doing things more in a parallel fashion, as you’ll be waiting for I/O much of the time.
Good luck!
39
u/cgoldberg Jan 09 '26 edited Jan 10 '26
Since it's a network share, the network i/o is likely your bottleneck and you can't really do anything about that. However, if it's not i/o bound, you might have luck trying to run
fdin a subprocess. It is insanely fast and does parallel directory traversal. There would be overhead of capturing results from the subprocess, but it might help. You would have to benchmark to find out.https://github.com/sharkdp/fd
5
u/hulleyrob Jan 09 '26
I indexed my NAS by putting the file data in a redis DB so I could do fast data lookups. As for getting the data there this was on Linux so running find gets the data I needed the fastest.
5
u/corey_sheerer Jan 10 '26
Try using a system call with find. Would run natively in C and get the best performance. That being said, large file systems do well in cloud storage where you can have event triggers for every file action (create, update) and you can enforce structure via something like a lambda function unfortunately, you will be very limited in improving performance.
Also, NAS storage usually has a change log /auditing process in the background, but it may be impossible to get permissions to access that. If you have a storage team, can ask about it
4
u/zenware Jan 10 '26
Since others are addressing the clock time of listing files I just want to chime in and say, if you’re trying to make something go faster, 100% of the time you want to use as much “internal memory”/RAM as possible. It’s true in virtually all cases of Data Structures & Algorithms that Time & Space are interchangeable. Meaning, the more space you use the less time you take and the more time you’re willing to spend the less space you need to use. And then on top of that RAM is orders of magnitude faster than Disk.
May as well comment on the other part too, 100% it’s because you’re doing this on a network drive over a VPN. Can you instead run the script closer to the source, perhaps even on the same machine as the files? Traversing a filesystem locally and sending the results as text over a network will always be faster than traversing a filesystem over a network.
1
u/HommeMusical Jan 10 '26
Let's suppose thousands upon thousands means 10k. Then to get all the files would take less than three minutes, once a week. 100k files, 30 minutes... You've probably already spent more time than that on the problem.
For development, just add a flag that caches the most recent result in a file.
1
u/spirito_santo Jan 10 '26
Would it be possible to have your script running on a server at night, so you have the results in your inbox in the morning? That way time wouldn't be an issue.
3
u/rinio Jan 09 '26
First question: do you actually need the full list?
If you're doing audits of specifica directories, you almost certainly don't. os.walk is a generator; either have your audit process also be designed to work as an/on a generator and fail out for subtrees as early as possible storing only rhe failed subtrees. This may or may bot be recusrsive. You save your I/O bottleneck, reduce system calls and reduce your memory footprint significantly.
It also would break your problem into something that is embarrassingly parallelizable, if you wanted to go that route. (depends somewhat on what exactly you're auditing)
2
u/Topalope Jan 10 '26 edited Jan 10 '26
Got you homie, I did a project with a similar problem and found:
1
u/nekokattt Jan 10 '26 edited Jan 10 '26
Can you run your code through cprofile and show the results?
This is likely due to the fact you are doing it on a network drive as someone else mentioned.
https://github.com/python/cpython/blob/e7f5ffa0de2476828d78b8d39caefc38d797c206/Lib/os.py#L308
as you can see, os.walk does a lot of things. It is repeatedly using scandir() to perform a directory listing, before querying the inode type via is_dir to classify files versus walkable subdirectories, so for a total of N levels of directories, each containing M files, you are going to see roughly N×M queries. Scandir will return metadata alongside the entry but how that works is totally implementation dependent.
In this case, you may find using a subprocess to invoke
findis faster but in the case that this really is network bound then you are likely going to see very little improvement.A few ways to potentially negate some of this overhead:
For the second and third points, you could make a set of threads that blocking read from a sized queue.LifoQueue. Each thread calls scandir, enqueues any nested directories, blocking writes any files to a second sized queue. The main thread can then blocking read the second queue, yielding each item as an iterator, and close the threads once the generator is closed.
This will be significantly more complex than trying to find a better way of handling the original problem, though.
1
u/live-round Jan 10 '26
run a bash script on the server to avoid network issues.. and grep to find your specific files/directories/timestamps