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`。