So I have a variable that holds the image path as a string. but I get the below error while trying to read the image using the path variable. The path variable is coming from another function that calls this code.
Error:
can't open/read file: check file path/integrity
My code:
path = "D://dev//py_scripts//SS1.jpg"
image=cv2.imread(path)
Tried several solutions but ended up with same error.
Double forward slashes make the path invalid.
Use single forward slashes. That is commonly tolerated on Windows, which natively wants backslashes.
Double backslashes are only what you see. They're actually single backslashes in the path/string, but the string syntax requires escaping backslashes (and other stuff) by a preceding backslash, so that's why one has to use double backslashes in most string literals...
Python has "r-strings" ("raw" strings). In a raw string, even backslashes are taken literally, and nothing is escapable (a matching quote character ends the string, always).
"D:/dev/py_scripts/SS1.jpg"
r"D:\dev\py_scripts\SS1.jpg"
"D:\\dev\\py_scripts\\SS1.jpg"
import cv2
path1= "SS1.jpg"
#sometimes doesnt work depends on the compiler. If its on sub folder #py_scripts\SS1.jpg
or
path2= "d:\dev\py_scripts\SS1.jpg"
image = cv2.imread(path2)
If you want to use path1 method, and set it to work 100%
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
I would suggest changing the format of the path as follows:
import cv2
#Several options
path = r"D:\dev\py_scripts\SS1.jpg"
path = r"D:/dev/py_scripts/SS1.jpg"
path = "D:/dev/py_scripts/SS1.jpg"
image=cv2.imread(path)
But based on the error you are getting, you need to check the format of the image and its integrity, as the error says. That means you must be able to open the image without issues on an editor like Windows Photos to check if the file is not corrupted.
Related
x = open('Homework','r')
print(x.name)
x.close()
I got this error when I run the code.
File "C:/Users/LENOVO/Desktop/pythonhome/tobechanged.py", line 16, in <module>
x = open('Homework','r')
FileNotFoundError: [Errno 2] No such file or directory: 'Homework'
SO I tried to type the full path
x = open('C:\Users\LENOVO\Desktop\pythonhome','r')
print(x.name)
x.close()
I got an Unicode error.
btw I'm using windows.
As the comments mentioned, it's usually good to type out the full path to the file, because running a script in IDLE, for example, can cause Python to search for the file in a directory that you are not intending. The reason you got the Unicode error is because you are using a special character, the backslash (\) which starts something known as an escape sequence. Escape sequences allow coders to specify special characters, like the newline character: \n. You can read more about these in Python's docs here
You have to either use a raw string (a string preceded with r, like this r'C:\Users\...'), or escape these characters with double backslashes, like this: C:\\Users\\....
Additionally, you need to specify the extension for the Homework file, otherwise the file system won't be able to find the file you are referring to, resulting in the FileNotFoundError you encountered. As #tdelaney mentioned, these extensions may be hidden by default in Windows Explorer.
Also, the recommended way in Python to open files is using the with statement, as this handles closing the object for you. Here is a sample (assuming that the extension of the Homework file is .txt):
with open('C:\\Users\\LENOVO\\Desktop\\pythonhome\\Homework.txt', 'r') as x:
print(x.name)
It is because you are forgetting the extension to the file (the ending of it). For example, if you have a text file that is named Homework, you would include it in like this
open(r'Homework.txt','r')
For this example, it must be in the same directory as your script. If you wanted to open a file outside of your scripts directory, you would have to find the full path of it. Here is an example of the Homework.txt file in my downloads folder.
open(r'C:\Users\USER\Downloads\Homework.txt','r')
You can also see in this code I use an r infront of the path. This tells Python the expression is a raw string and escape sequences are not parsed.
I am using Python 3.3 on Windows 7.
Here is the problem.
When I have a filename starting with a number it changes wrong.
For example:
>>> 'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\x01.jpg'
I am aware that I can fix it manually by adding an escaping backslash.
>>> 'E:\DOCUMENTS\\1.jpg'
'E:\\DOCUMENTS\\1.jpg'
Or by adding "r" in front of the string.
>>> r'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\\1.jpg'
But I cannot do it manually, because I don't know what the path will be.
What are the possible solutions?
UPDATE:
As #Blender suggested, I was going to post the code. When I rewrote it, I realized that originally there was a mistake, that leaded me to a wrong conclusion. As far as I have understood, the described above situation, when it is necessary to make a string with a path raw dynamically does not happen. It can only happen when the path is written manually.
import os
from PIL import Image as PIL
from PIL import ImageTk
def searchforimages(dir):
imagelist=[]
for file in os.listdir(dir):
fileabspath=os.path.join(dir,file)
try:
# the problem was here originally, but now it is ok.
# since "fileabspath" get passes as a raw string,
# so there is no problem for PIL.open() to open it
PIL.open(fileabspath)
imagelist.append(fileabspath)
except:
continue
return imagelist
searchforimages('E:\photos')
#the problem only happens, when path is written manually
path='E:\photos\1.jpg'
PIL.open(path)
So now I just want to confirm, the problem when it is necessary to make a string with a path raw dynamically never really happens, does it?
\ only matters when it is used in string literal.
>>> path = input() # `a\n\1` in the following line is typed by me (user).
a\n\1
>>> path
'a\\n\\1'
I am working on a python script that installs an 802.1x certificate on a Windows 8.1 machine. This script works fine on Windows 8 and Windows XP (haven't tried it on other machines).
I have isolated the issue. It has to do with clearing out the folder
"C:\Windows\system32\config\systemprofile\AppData\LocalLow\Microsoft\CryptURLCache\Content"
The problem is that I am using the module os and the command listdir on this folder to delete each file in it. However, listdir errors, saying the folder does not exist, when it does indeed exist.
The issue seems to be that os.listdir cannot see the LocalLow folder. If I make a two line script:
import os
os.listdir("C:\Windows\System32\config\systemprofile\AppData")
It shows the following result:
['Local', 'Roaming']
As you can see, LocalLow is missing.
I thought it might be a permissions issue, but I am having serious trouble figuring out what a next step might be. I am running the process as an administrator from the command line, and it simply doesn't see the folder.
Thanks in advance!
Edit: changing the string to r"C:\Windows\System32\config\systemprofile\AppData", "C:\Windows\System32\config\systemprofile\AppData", or C:/Windows/System32/config/systemprofile/AppData" all produce identical results
Edit: Another unusual wrinkle in this issue: If I manually create a new directory in that location I am unable to see it through os.listdir either. In addition, I cannot browse to the LocalLow or my New Folder through the "Save As.." command in Notepad++
I'm starting to think this is a bug in Windows 8.1 preview.
I encountered this issue recently.
I found it's caused by Windows file system redirector
and you can check out following python snippet
import ctypes
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
#Example usage
import os
path = 'C:\\Windows\\System32\\config\\systemprofile\\AppData'
print os.listdir(path)
with disable_file_system_redirection():
print os.listdir(path)
print os.listdir(path)
ref : http://code.activestate.com/recipes/578035-disable-file-system-redirector/
You must have escape sequences in your path. You should use a raw string for file/directory paths:
# By putting the 'r' at the start, I make this string a raw string
# Raw strings do not process escape sequences
r"C:\path\to\file"
or put the slashes the other way:
"C:/path/to/file"
or escape the slashes:
# You probably won't want this method because it makes your paths huge
# I just listed it because it *does* work
"C:\\path\\to\\file"
I'm curious as to how you are able to list the contents with those two lines. You are using escape sequences \W, \S, \c, \s, \A in your code. Try escaping the back slash like this:
import os
os.listdir('C:\\Windows\\System32\\config\\systemprofile\\AppData')
I have a small problem with reading in my file. My code:
import csv as csv
import numpy
with open("train_data.csv","rb") as training:
csv_file_object = csv.reader(training)
header = csv_file_object.next()
data = []
for row in csv_file_object:
data.append(row)
data = numpy.array(data)
I get the error no such file "train_data.csv", so I know the problem lies with the location. But whenever I specify the pad like this: open("C:\Desktop...etc) it doesn't work either. What am I doing wrong?
If you give the full file path, your script should work. Since it is not, it must be that you have escape characters in your path. To fix this, use a raw-string to specify the file path:
# Put an 'r' at the start of the string to make it a raw-string.
with open(r"C:\path\to\file\train_data.csv","rb") as training:
Raw strings do not process escape characters.
Also, just a technical fact, not giving the full file path causes Python to look for the file in the directory that the script is launched from. If it is not there, an error is thrown.
When you use open() and Windows you need to deal with the backslashes properly.
Option 1.) Use the raw string, this will be the string prefixed with an r.
open(r'C:\Users\Me\Desktop\train_data.csv')
Option 2.) Escape the backslashes
open('C:\\Users\\Me\\Desktop\\train_data.csv')
Option 3.) Use forward slashes
open('C:/Users/Me/Desktop/train_data.csv')
As for finding the file you are using, if you just do open('train_data.csv') it is looking in the directory you are running the python script from. So, if you are running it from C:\Users\Me\Desktop\, your train_data.csv needs to be on the desktop as well.
pd.read_csv('C:\Users\aaa\Desktop\contrylist.csv')
plz help guys.I am a beginner in pandas..i am not able to open this csv files.
Also I want to ask which is default directory for anacondas where I can store files and open them in below format
pd.read_csv('contrylist.csv')
If you don't want to put the full path, the file needs to be in the current directory, which you can see from
import os
os.path.abspath(os.path.curdir)
To change the current directory, use os.chdir
os.chdir(r'C:\Users\aaa\Desktop')
By the way, if you use IPython, then you can just use %pwd to see the current directory and %cd to change it.
Double your backslashes.
pd.read_csv('C:\\Users\\aaa\\Desktop\\contrylist.csv')
Or use raw strings:
pd.read_csv(r'C:\Users\aaa\Desktop\contrylist.csv')
Backslash is a special character in string literals and it's used for escaping. You should read the docs: strings and string literals.