Python FileNotFoundError how to handle long filenames

Question:

I have a weird problem. I can neither rename specific files, nor remove them. I get the FileNotFoundError.

Similar questions have been asked before. The solution to this problem was using a full path and not just the filename.

My script worked before using only the filenames, but using different files I get this error, even using the full path.

It seems, that the filename is causing the error, but I cannot resolve it.

import os

cwd = os.getcwd()

file = "003de5664668f009cbaa7944fe188ee1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3."
change = "student_1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3."

oldname = os.path.join(cwd,file)
newname = os.path.join(cwd,change)

print(file in os.listdir())
print(os.path.isfile(file))
os.rename(oldname, newname)

I get the following output:

True
False
Traceback (most recent call last):
  File "C:UsersXDesktopcodesubtest.py", line 13, in <module>
    os.rename(oldname, newname)
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden: 'C:\Users\X\Desktop\code\sub\003de5664668f009cbaa7944fe188ee1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3.' -> 'C:\Users\X\Desktop\code\sub\student_1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3.'
[Finished in 0.4s with exit code 1]

This file is existing if I use windows search in the folder.
If I try to use the full path I also get an windows error not finding the file.

I have also tried appending a unicode string u”+filename to the strings, because it was suggested by an user.

The pathlength is < 260, so what is causing the problem?

Asked By: Ali

||

Answers:

This isn’t exactly an answer (I lack the rep for that) but…

Two thoughts:

A) Are those file names supposed to end with periods?

B) Instead of escaping backslashes, you can use forward slashes here (i.e., C:/…/…/…)

Answered By: Quentin

This is a windows/Python thing. Filenames with a trailing period are sometimes trimmed.

If this is a once-off task, you can use two trailing periods as a workaround.

Answered By: wim

I created a function that supports Windows huge paths:

def support_for_large_paths(dos_path, encoding=None):
    """
    Function returns a path that supports up to 32,760 characters
    
    https://stackoverflow.com/questions/36219317/pathname-too-long-to-open"""
    if (not isinstance(dos_path, str) and encoding is not None): 
        dos_path = dos_path.decode(encoding)
    path = os.path.abspath(dos_path)
    if path.startswith(u"\\"):
        return u"\\?\UNC\" + path[2:]
    return u"\\?\" + path

Use:

mylargepath = "C:UsersgabrielOther - MASS PATH ITS A MANY CHARSProjectsMyBigDirmysubdirthis is my file with the incredibly large name.pdf"

print(support_for_large_paths(mylargepath))
>>> \?C:UsersgabrielOther - MASS PATH ITS A MANY CHARSProjectsMyBigDirmysubdirthis is my file with the incredibly large name.pdf
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.