How to find the smallest file in a directory in Python
Sometime while creating a program or writing a script in Python we need to find the largest file in a current directory. This is very simple task and can done by running a following script:
import os
files = os.listdir(".")
smallest_file_size = 10000
smallest_file = ""
for file in files:
if os.path.isfile(file):
size = os.path.getsize(file)
if size < smallest_file_size:
smallest_file_size = size
smallest_file = file
print("the smallest file in current directory has filename "+smallest_file+ " and size: "+str(smallest_file_size)+" bytes.")
What does that code?
First, we are making a list of files in a current directory using os
module. In order to understand, what does further code, we have to check, what kind of object we get by running os.listdir()
command.
Let's check is separately:
>>> import os
>>> files = os.listdir(".")
>>> type(files)
<type 'list'>
Ok, now we see, that listdir()
method is returning a list. It's good information, because now we know, that we can work with files variable as with a list. In further code we a looping a list (for file in files).