Issue
Let's take the case I should print the number of bytes taken by PDF files in the directory tree (".pdf" extensions). I wrote down the following code which seems to work but, I am not sure it returns what I am looking for.
import os
def find_pdf_size(files):
for root, dirs, files in os.walk(top):
for name in files:
if name.endswith(".pdf"):
print(os.path.getsize(top))
top = 'C:/Users/PC/Desktop/Preludium/Preludium(2)/Articles/MM'
print(find_pdf_size(top))
Since this code returns always the same number, repeated for the number of files within the file folder, I suppose. Could you please let me know how to move out of this?
Solution
Your code
import os
def find_pdf_size(files):
for root, dirs, files in os.walk(top):
for name in files:
if name.endswith(".pdf"):
print(os.path.getsize(top))
top = 'C:/Users/PC/Desktop/Preludium/Preludium(2)/Articles/MM'
print(find_pdf_size(top))
does report size of top
which does not change so you get repeated value use os.path.join
to get path to file you want to measure, that is do
import os
def find_pdf_size(files):
for root, dirs, files in os.walk(top):
for name in files:
if name.endswith(".pdf"):
print(os.path.getsize(os.path.join(root,name)))
top = 'C:/Users/PC/Desktop/Preludium/Preludium(2)/Articles/MM'
print(find_pdf_size(top))
From os.walk
docs
Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name)
.
Answered By - Daweo Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.