Win 环境 python 读取文件路径超长报错 NotFoundError

1、缩减文件路径的长度

Windows 提供了短路径名,可以通过 `os.path` 模块获取短路径名。

import os

def get_short_path_name(long_path):
    import ctypes
    from ctypes import wintypes

    _GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
    _GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
    _GetShortPathNameW.restype = wintypes.DWORD

    output_buf_size = 0
    while True:
        output_buf = ctypes.create_unicode_buffer(output_buf_size)
        needed = _GetShortPathNameW(long_path, output_buf, output_buf_size)
        if needed == 0:
            raise ctypes.WinError()
        if needed <= output_buf_size:
            return output_buf.value
        else:
            output_buf_size = needed

long_path = r"C:\path\to\your\very\long\path"
short_path = get_short_path_name(long_path)
print(short_path)

2、使用 UNC 路径

windows下文件路径的最大长度是260,

在绝对路径的前加上  "\\?\" , 告诉计算机使用最大的路径长度,这样就不会出现路径太长而导致的报 " FileNotFoundError" 的问题了。

#coding=utf-8
import os

def convert_to_unc_path(path):
    if not path.startswith('\\\\?\\'):
        path = '\\\\?\\' + os.path.abspath(path)
    return path

long_path = r"C:\path\to\your\very\long\path"
unc_path = convert_to_unc_path(long_path)
print(unc_path)


对于共享计算机目录: \\+计算机名+路径(例如\\zhangsan\test

在共享路径前面加上 \\?\UNC\ 这样就ok了,注意需要把共享计算机的前面的\\去掉.

比如: \\?\UNC\zhangsan\test

3. 修改注册表

在 Windows 10 及以上版本,可以通过修改注册表来启用长路径支持。

可以通过以下步骤启用长路径支持:
1. 打开注册表编辑器(`regedit`)。
2. 导航到 `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`。
3. 找到或创建一个名为 `LongPathsEnabled` 的 `DWORD` 值。
4. 将其值设置为 `1`。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值