本文目录导读:

Python(最常用)
import os
# 方法1:使用 os.path.getsize()
file_size = os.path.getsize('example.txt')
print(f"文件大小: {file_size} 字节")
# 方法2:使用 os.stat()
file_stat = os.stat('example.txt')
file_size = file_stat.st_size
print(f"文件大小: {file_size} 字节")
# 方法3:获取更友好的格式
def human_readable_size(size):
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} TB"
print(f"文件大小: {human_readable_size(file_size)}")
Bash/Shell
#!/bin/bash
# 方法1:使用 stat 命令(Linux)
file_size=$(stat -c%s "example.txt")
echo "文件大小: $file_size 字节"
# 方法2:使用 wc -c 命令
file_size=$(wc -c < "example.txt")
echo "文件大小: $file_size 字节"
# 方法3:使用 ls -l 命令
file_size=$(ls -l "example.txt" | awk '{print $5}')
echo "文件大小: $file_size 字节"
# macOS 专用语法
# file_size=$(stat -f%z "example.txt")
Node.js
const fs = require('fs');
// 方法1:同步方式
const stats = fs.statSync('example.txt');
console.log(`文件大小: ${stats.size} 字节`);
// 方法2:异步方式
fs.stat('example.txt', (err, stats) => {
if (err) throw err;
console.log(`文件大小: ${stats.size} 字节`);
});
// 方法3:使用 fs.promises
const fsPromises = require('fs').promises;
async function getFileSize() {
const stats = await fsPromises.stat('example.txt');
console.log(`文件大小: ${stats.size} 字节`);
}
PowerShell
# 方法1:使用 Get-Item $file = Get-Item "example.txt" $fileSize = $file.Length Write-Host "文件大小: $fileSize 字节" # 方法2:使用 Get-Content + Measure-Object $fileSize = (Get-Content "example.txt" | Measure-Object -Character).Characters Write-Host "文件大小: $fileSize 字节" # 方法3:更详细的信息 $fileInfo = Get-Item "example.txt" $sizeKB = [math]::Round($fileInfo.Length / 1KB, 2) $sizeMB = [math]::Round($fileInfo.Length / 1MB, 2) Write-Host "文件大小: $($fileInfo.Length) 字节 ($sizeKB KB, $sizeMB MB)"
PHP
<?php
// 方法1:使用 filesize()
$file_size = filesize('example.txt');
echo "文件大小: $file_size 字节\n";
// 方法2:使用 fstat()
$handle = fopen('example.txt', 'r');
$file_stat = fstat($handle);
fclose($handle);
echo "文件大小: {$file_stat['size']} 字节\n";
// 方法3:格式化大小
function formatSize($bytes) {
$units = ['B', 'KB', 'MB', 'GB'];
$unitIndex = 0;
while ($bytes >= 1024 && $unitIndex < count($units) - 1) {
$bytes /= 1024;
$unitIndex++;
}
return round($bytes, 2) . ' ' . $units[$unitIndex];
}
echo "文件大小: " . formatSize($file_size) . "\n";
?>
Ruby
# 方法1:使用 File.size
file_size = File.size("example.txt")
puts "文件大小: #{file_size} 字节"
# 方法2:使用 File.stat
stat = File.stat("example.txt")
puts "文件大小: #{stat.size} 字节"
Go
package main
import (
"fmt"
"os"
)
func main() {
// 获取文件信息
fileInfo, err := os.Stat("example.txt")
if err != nil {
fmt.Println("错误:", err)
return
}
// 获取文件大小
fileSize := fileInfo.Size()
fmt.Printf("文件大小: %d 字节\n", fileSize)
// 格式化大小
sizeMB := float64(fileSize) / (1024 * 1024)
fmt.Printf("文件大小: %.2f MB\n", sizeMB)
}
使用建议
- 跨平台:Python 是最通用的选择,在 Windows、Linux、macOS 上都能运行
- Linux 系统:Bash 命令最快捷
- Windows 系统:PowerShell 或 Python 都很方便
- 需要处理大量文件:建议使用 Python 或 Node.js,便于批量处理
选择哪种方法取决于你的使用场景和已有环境,如果需要更详细的文件信息(如修改时间、权限等),stat 类方法会更有优势。