Lecture 27
Lecture 27
Lecture 27
Lecture Outline
• Recursion
– CS1001 Lecture 27 –
Finding the size of a directory (folder)
– CS1001 Lecture 27 – 1
A sample directory structure
courses
comp1001 comp1002
my_code2.py
– CS1001 Lecture 27 – 2
Finding the size of a directory (folder)
– CS1001 Lecture 27 – 3
The os module
• os.path.isfile(f)
returns True if f is a file.
• os.path.isdir(f)
returns True if f is a directory.
• os.path.join(path,f)
returns the full name of f (including path).
• os.path.getsize(f)
returns the size of the file f.
• os.listdir(f)
returns a list of the subdirectories and files under
the directory f.
– CS1001 Lecture 27 – 4
Finding the size of a directory (folder)
import os
def getSize(f):
size = 0
if os.path.isfile(f): # base case - f is a file
return os.path.getsize(f) # add file size
elif os.path.isdir(f): # f is a directory
lst = os.listdir(f) # get contents of f
for i in lst:
new_f = os.path.join(f,i)
size += getSize(new_f) # recursive calls
return size
else: # base case - f does not exist
print(f, " does not exist.")
return size
# Main program
file = input("Enter a file name or directory name: ")
print("The size of ", file, " is ", getSize(file), " bytes")
– CS1001 Lecture 27 – 5
Finding the size of a directory (folder)
Directory courses :
[’comp1002’, ’comp1001’]
Calling getSize on courses/comp1002
Directory courses/comp1002 :
[’assign02’, ’assign01’]
Calling getSize on courses/comp1002/assign02
Directory courses/comp1002/assign02 :
[’output.txt’]
Calling getSize on courses/comp1002/assign02/output.txt
File courses/comp1002/assign02/output.txt size= 46
Calling getSize on courses/comp1002/assign01
Directory courses/comp1002/assign01 :
[’my_file.txt’]
Calling getSize on courses/comp1002/assign01/my_file.txt
File courses/comp1002/assign01/my_file.txt size= 34
Calling getSize on courses/comp1001
Directory courses/comp1001 :
[’lab02’, ’lab01’, ’assign01’]
Calling getSize on courses/comp1001/lab02
Directory courses/comp1001/lab02 :
[’my_code.py’]
Calling getSize on courses/comp1001/lab02/my_code.py
File courses/comp1001/lab02/my_code.py size= 30
Calling getSize on courses/comp1001/lab01
Directory courses/comp1001/lab01 :
[’example.txt’, ’code’]
Calling getSize on courses/comp1001/lab01/example.txt
File courses/comp1001/lab01/example.txt size= 20
Calling getSize on courses/comp1001/lab01/code
Directory courses/comp1001/lab01/code :
– CS1001 Lecture 27 – 6
[’my_code2.py’, ’my_code1.py’]
Calling getSize on courses/comp1001/lab01/code/my_code2.py
File courses/comp1001/lab01/code/my_code2.py size= 47
Calling getSize on courses/comp1001/lab01/code/my_code1.py
File courses/comp1001/lab01/code/my_code1.py size= 37
Calling getSize on courses/comp1001/assign01
Directory courses/comp1001/assign01 :
[’data.dat’]
Calling getSize on courses/comp1001/assign01/data.dat
File courses/comp1001/assign01/data.dat size= 12
The size of courses is 226 bytes
– CS1001 Lecture 27 – 7
Recursion vs. Iteration
– CS1001 Lecture 27 – 8