I am practicing with the os
module and more specifically os.walk()
. I am wondering if there is an easier/more efficient way to find the actual path
Your work around should work fine, but a simpler way to do this would be:
import os
threshold_size = 500
root = os.getcwd()
root = os.path.abspath(root) # redunant with os.getcwd(), maybe needed otherwise
for folder, subfolders, files in os.walk(root):
for file in files:
filePath = os.path.join(folder, file)
if os.path.getsize(filePath) >= threshold_size:
print filePath, str(os.path.getsize(filePath))+"kB"
The basic idea here is that folder
will be an absolute normalized path if the argument to os.walk
is one and os.path.join
will produce an absolute normalized path if any of the arguments is an absolute path and all the following arguments are normalized.
The reason why os.path.abspath(file)
doesn't work in your first example is that file
is a bare filename like quiz.py
. So when you use abspath
it does essentially the same thing os.path.join(os.getcwd(), file)
would do.