在 Python 中创建路径长度超过 260 个字符的目录

Create directory with path longer than 260 characters in Python

这个问题与 this one, but for Python instead of powershell. It was also discussed here, and 非常相似,但没有发布有效的解决方案。

那么,有没有办法在 Python 中创建一个目录来绕过 windows 的 260 个字符限制?我尝试了多种前置 \?\ 的方法,但无法使其工作。

特别是下面最明显的代码

path = f'\\?\C:\{"a"*300}.txt'
open(path, 'w')

因错误而失败

OSError: [Errno 22] Invalid argument: '\\?\C:\aaaaa<...>aaaa.txt'

感谢 eryksun,我意识到我正在尝试创建一个名称太长的文件。经过一些实验,这就是如何在 windows 上创建超过 260 个字符的路径(前提是文件系统允许):

from pathlib import Path

folder = Path('//?/c:/') / ('a'*100) / ('b'*100)
file = folder / ('c' * 100)

folder.mkdir(parents=True, exist_ok=True)
file.open('w')