You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何列出系统所有磁盘的全部文件?可通过CMD/Python/Powershell实现吗

全磁盘文件遍历实现方案

你可以通过CMD、PowerShell、Python三种方式完成全盘符文件遍历需求,具体实现如下:

1. CMD实现

CMD可结合磁盘查询命令和目录遍历命令完成,以下命令会自动识别所有存在的NTFS/FAT32格式盘符,递归输出所有文件的完整路径,最终结果保存到D:\all_files.txt:

@echo off
setlocal enabledelayedexpansion
:: 获取所有可用盘符
for /f "skip=1 delims=:" %%i in ('wmic logicaldisk get name') do (
    set "drive=%%i:"
    if exist !drive! (
        :: 遍历当前盘符所有文件,追加输出到结果文件
        dir /s /b /a-d !drive! >> D:\all_files.txt
    )
)
echo 遍历完成,结果已保存到D:\all_files.txt
pause

参数说明:/s表示递归遍历子目录,/b表示只输出文件完整路径,/a-d表示排除文件夹只保留文件。

2. PowerShell实现

PowerShell的实现逻辑更简洁,支持自动跳过无权限访问的目录,结果可导出为TXT或CSV格式:

# 获取所有有盘符的本地磁盘
$drives = Get-Volume | Where-Object { $_.DriveLetter -ne $null } | ForEach-Object { $_.DriveLetter + ":\" }
# 递归遍历所有文件,跳过权限错误
Get-ChildItem -Path $drives -File -Recurse -ErrorAction SilentlyContinue | Select-Object FullName, Length, LastWriteTime | Export-Csv -Path "D:\all_files.csv" -NoTypeInformation -Encoding UTF8

如果只需要输出文件路径,可直接将结果输出到TXT:

Get-ChildItem -Path $drives -File -Recurse -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } | Out-File -FilePath "D:\all_files.txt" -Encoding UTF8

3. Python实现

可以用标准库os或pathlib完成,无需额外安装第三方依赖,以下示例会自动处理权限异常,最终结果写入到TXT文件:

import os
import string

def get_all_drives():
    # 获取所有可用盘符
    drives = []
    for c in string.ascii_uppercase:
        drive = f"{c}:\\"
        if os.path.exists(drive):
            drives.append(drive)
    return drives

def scan_all_files(output_path="D:\\all_files.txt"):
    drives = get_all_drives()
    with open(output_path, "w", encoding="utf-8") as f:
        for drive in drives:
            for root, dirs, files in os.walk(drive):
                for file in files:
                    try:
                        full_path = os.path.join(root, file)
                        f.write(full_path + "\n")
                    except PermissionError:
                        # 跳过无权限访问的文件
                        continue
    print(f"遍历完成,结果已保存到{output_path}")

if __name__ == "__main__":
    scan_all_files()

如果需要更快的遍历速度,也可以替换os.walk为pathlib.Path.rglob方法,逻辑一致。


内容的提问来源于stack exchange,提问作者Jr.Abdul Wahab Melethil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:15:04