如何创建用于定义 .pdf 大小的函数

How create a function for defining .pdf size

假设我应该打印目录树(“.pdf”扩展名)中 PDF 文件占用的字节数。我写下了以下似乎有效的代码,但我不确定 returns 我在寻找什么。

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))

因为这段代码 returns 总是相同的数字,重复了文件夹内的文件数,我想。你能告诉我如何摆脱这个吗?

您的代码

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))

是否报告 top 的大小,它不会改变,因此您获得重复值使用 os.path.join 获取您要测量的文件的路径,即 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))

来自 os.walk 文档

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).

试试这个。

import os


def sizeof_fmt(num, suffix="B"):
    for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
        if abs(num) < 1024.0:
            return f"{num:3.1f}{unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f}Yi{suffix}"


def find_pdf_size(path):
    for root, dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".pdf"):
                print(f"File name: {name} and its size: {sizeof_fmt(os.path.getsize(name))}")


path = 'C:/Users/PC/Desktop/Preludium/Preludium(2)/Articles/MM'
print(find_pdf_size(path))

或无格式

import os

def find_pdf_size(path):
    for root, dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".pdf"):
                print(f"File name: {name} and its size: {(os.path.getsize(name))}")


path = 'C:/Users/PC/Desktop/Preludium/Preludium(2)/Articles/MM'
print(find_pdf_size(path))

你在函数中传递参数时犯了一个小错误 get_size_of。使用以下函数更新您的代码

import os
path = r"C:\Users\HPvns\Desktop\cycle"
def print_size(path):
    for root, directories, files in os.walk(path, topdown=False):
        for name in files:
            if name.endswith(".pdf"):
                print(os.path.getsize(os.path.join(root, name)))