Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python FileNotFoundError how to handle long filenames

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:\Users\X\Desktop\code\sub\test.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?

like image 234
Ali Avatar asked Feb 22 '17 01:02

Ali


1 Answers

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.

like image 122
wim Avatar answered Sep 20 '22 11:09

wim