Методы получения размеров файлов в папке | Примеры кода на Python, JavaScript и PowerShell

Чтобы получить размеры файлов в папке, существует несколько способов в зависимости от используемого вами языка программирования. Вот примеры на Python, JavaScript и PowerShell:

  1. Python:

    import os
    folder_path = '/path/to/folder'
    # Method 1: Using os.listdir() and os.path.getsize()
    file_sizes = [(filename, os.path.getsize(os.path.join(folder_path, filename))) for filename in os.listdir(folder_path)]
    # Method 2: Using os.scandir()
    file_sizes = [(entry.name, entry.stat().st_size) for entry in os.scandir(folder_path) if entry.is_file()]
    # Displaying the file sizes
    for filename, size in file_sizes:
    print(f"{filename}: {size} bytes")
  2. JavaScript (Node.js):

    const fs = require('fs');
    const path = require('path');
    const folderPath = '/path/to/folder';
    // Using fs.readdirSync() and fs.statSync()
    const fileSizes = fs.readdirSync(folderPath)
    .filter(filename => fs.statSync(path.join(folderPath, filename)).isFile())
    .map(filename => {
    const filePath = path.join(folderPath, filename);
    const { size } = fs.statSync(filePath);
    return { filename, size };
    });
    // Displaying the file sizes
    fileSizes.forEach(({ filename, size }) => {
    console.log(`${filename}: ${size} bytes`);
    });
  3. PowerShell:

    $folderPath = 'C:\path\to\folder'
    # Using Get-ChildItem and Select-Object
    $fileSizes = Get-ChildItem -Path $folderPath | Where-Object { $_.PSIsContainer -eq $false } |
    Select-Object Name, Length
    # Displaying the file sizes
    $fileSizes | ForEach-Object {
    Write-Output ("$($_.Name): $($_.Length) bytes")
    }