PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 25, 2022

[FIXED] How create a function for defining .pdf size

 August 25, 2022     module, pdf, python, size     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing