Python FileNotFoundError how to handle long filenames - python

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?

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.

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:/.../.../...)

Related

can't get a file size in python

I am a python newbie and learning from "automate boring stuff" book, so it says in the book the I can use os.path.getsize(path) to get a file size but when I run this code it gives an error, can you please explain why I am getting this?
import os
mypath = 'C:\\Users\\C2D\\Desktop\\Embedded system\\u1.PNG'
os.chdir(mypath)
print(os.path.getsize(mypath))
error is :
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\C2D\Desktop\Embedded system\u1.PNG'
I am working on windows 8.1 and using python3.8 on pycharm
mypath is a file and not a folder.
With the command os.chdir(mypath) you are trying to change the folder - into an image.
It is generally very important, in which exact line an exception occurs. In this case it will be line 4.
To solve your problem: You can probably just delete this line.
It is failing because of the line os.chdir(mypath). You don't need to chdir().
Assuming the path is correct and the file exists, it should work (print the file size) if you remove the os.chdir() statement.

File not found Error in reading text in python [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
I am trying to read a text file on my hard drive via python with the following script:
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
But it is giving the following error:
IOError Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'
I also tried with other way:
with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
print f.read()
Ended up with the same error. The text file is present in the directory specified.
Replace
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
with
fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.
Another way to do it without a raw string is
fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")
This escapes the backslashes (i.e. "\\" => \).
An even better solution is to use the os module:
import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')
This creates your path in an os-independent way so you don't have to worry about those things.
One last note... in general, I think you should use the with construct you mentioned in your question... I didn't in the answer for brevity.
I was encountering same problem. This problem resulted due to different file path notation Python.
For example, filepath in Windows reads with backward slash like: "D:\Python\Project\file.txt"
But Python reads file path with forward slash like: "D:/Python/Project/file.txt"
I used r"filepath.txt" and "os.path.join" and "os.path.abspath" to no relief. os library also generates file path in Windows notation. Then I just resorted to IDE notation.
You don't encounter this error if "file.txt" is located in same directory, as filename is appended to working directory.
PS: I am using Python 3.6 with Spyder IDE on Windows machine.

how to escape single quote from string

This is my problem:
fpaths=os.listdir(ligand_names_list[0].replace("'", "\\'"))
OSError: [Errno 2] No such file or directory: "5-iodoindirubin-3\\'-oxime"
There is a file named 5-iodoindirubin-3'-oxime but I cannot make os.listdir() to find it. Here's another attempt I made inspired by this thread Adding backslashes without escaping [Python] :
fpaths=os.listdir(ligand_names_list[0].__ repr __())
OSError: [Errno 2] No such file or directory: '"5-iodoindirubin-3\'-oxime"'
The problem in this case is the leading single quotes which I don't know how to remove them. Any idea?
You don't have to escape anything; you only have to escape things when entering string literals into your code. Once the string has the right value, you can just use it as it is.
Is the file in the current directory, or in some other directory? (The current directory is the same directory your Python script is in, unless you've changed it.) If it's not in the current directory, that would explain why it's not being found.
(You say it's a file; I hope it is a directory, since you're calling os.listdir() on it...)

Weird python error - I/O error No such file of directory

I am trying to open python prompt and run the below code:
>>> a=open("Andrew_Smith_(author/education_professional)_0",'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory:
'Andrew_Smith_(author/education_professional)_0'
I am not sure why I am getting the error. I know the file contains special characters, but I am asking it to create a new file.
Edit:
I cannot use -, as some names might contain '-'. I also don't want to use space. Is there any other alternative?
As others have said the issue is the /, it is looking for a directory named Andrew_Smith_(author to create the new file education_professional)_0 in.
bash-3.2# mkdir "Andrew_Smith_(author"
bash-3.2# python
>>> a=open("Andrew_Smith_(author/education_professional)_0", 'w')
>>>
Because you have a / character in your filename. Neither *NIX nor Windows typically allow this.
I believe there are two problems here. First is because of the '/' character. It can't distinguish between / in a file name (which isn't valid) and / as a path seperator. And second, I don't believe '(' or ')' are valid in path names either.
The problem is that you are using reserved characters -- remove the / (or replace it with, for example, -) and everything should just work.

Rename invalid filename in XP via Python

My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to my XP SP3 machine,
and some of the file names have "?" replacing/representing invalid characters.
I tried to use Python to os.rename the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.
i.e.:
>>> os.chdir(r'F:\recovery\My Music')
>>> os.listdir(u'.')
[u'Don?t Be Them.mp3', u'That?s A Soldier.mp3']
>>> blah=os.listdir(u'.')
>>> blah[0]
Don?t Be Them.mp3
>>> os.rename(blah[0],'dont be them.mp3')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
os.rename(blah[0],'dont be them.mp3')
WindowsError: [Error 123] The filename, directory name, or
volume label syntax is incorrect
I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.
Is there a way to handle these renames without knowing the original language?
'?' is not valid character for filenames. That is the reason while your approach failed.
You may try to use DOS short filenames:
import win32api
filelist = win32api.FindFiles(r'F:/recovery/My Music/*.*')
# this will extract "short names" from WIN32_FIND_DATA structure
filelist = [i[9] if i[9] else i[8] for i in filelist]
# EXAMPLE:
# this should rename all files in 'filelist' to 1.mp3, 2.mp3, 3.mp3, ...
for (number, filename) in enumerate(filelist):
os.rename(filaname, '%d.mp3' % (number))
Try passing a unicode string:
os.rename(blah[0], u'dont be them.mp3')

Categories