Python Pathlib glob在长路径名上失败,如何忽略错误?



我试图遍历一个"exFAT"Windows 10的格式化驱动器

from pathlib import Path
def scan_drive(drive_letter):
for f in Path(f"{drive_letter}:\").glob("**/*"):
# do something, code removed, print instead
print(f.name)
result = scan_drive('E')

当这段代码达到一个很长的文件路径名(在我的示例中是264个字符)时,作业崩溃出现FileNotFound错误。

File "C:dataPyCharmProjectsdrivescan_pysrcscan_drive.py", line 85, in scan_and_dump
result = scan_drive(f'{drive_letter}:\')
File "C:dataPyCharmProjectsdrivescan_pysrcscan_drive.py", line 38, in scan_drive
for f in Path(drive_path).glob("**/*"):
File "C:Program FilesPython39libpathlib.py", line 1167, in glob
for p in selector.select_from(self):
File "C:Program FilesPython39libpathlib.py", line 601, in _select_from
for p in successor_select(starting_point, is_dir, exists, scandir):
File "C:Program FilesPython39libpathlib.py", line 548, in _select_from
with scandir(parent_path) as scandir_it:
FileNotFoundError: [WinError 3] Das System kann den angegebenen Pfad nicht finden: 'E:\laptop\c\ProgramData\..."

我猜Windows不能以这种方式读取长度超过256字节的路径。

我希望在使用pathlib的glob中忽略长路径(和其他错误,如权限)这样我就可以浏览剩下的文件了。

我可以修复这个使用pathlib不写我自己的步行者?

我最终使用os。如果pathlib的glob运行了整个驱动器而没有出现问题,则用它来代替。

可能是因为操作系统的默认行为。Walk是忽略错误

import os
# replacement for
# for f in Path(drive_path).glob("**/*"):
drive_path = "e:\"
for root, dirs, files in os.walk(drive_path):
for file in files:
f = Path(root, file)
# do somethin
print(f.name)

最新更新