psarka
psarka

Reputation: 1842

Create directory with path longer than 260 characters in Python

This is very similar question to this one, but for Python instead of powershell. It was also discussed here, and here, but no working solutions are posted.

So, is there a way to create a directory in Python that bypasses the 260 char limit on windows? I tried multiple ways of prepending \\?\, but could not make it work.

In particular, the following most obvious code

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

fails with an error

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

Upvotes: 3

Views: 3218

Answers (2)

Eitan
Eitan

Reputation: 95

I had a problem with the limit and I disabled this limit, because the r'\\?\' didn't help me. So as I found this question I want to answer it for others, and I did this tutorial

What helped me in the tutorial is the second solution so I will write it here: Type in the search "gpedit.msc" and go to: Computer Configuration > Administrative Templates > System > Filesystem.

There you need to enable the "Enable Win32 long paths", close the editor and restart computer

The other solution is throuh the regisry editor, it can help: Type regedit in the search bar and goto

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem 

change the key 'LongPathsEnabled' to 1. or simply run this command:

reg add HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v LongPathsEnabled /t REG_DWORD /d 1

Good luck!

Upvotes: 0

psarka
psarka

Reputation: 1842

Thanks to eryksun I realized that I was trying to create a file with too long of a name. After some experiments, this is how one can create a path that exceeds 260 chars on windows (provided file system allows it):

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')

Upvotes: 3

Related Questions