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'
Related
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.
I have looked and tried different methods posted online but I cant get this to work.
This is my file path:
file_path = '\\something.com\1400_somethingelse\1400_somethingyes\1400_Design\1500_sketch\ShotCam'
This file path is going to change multiple times so I need this to become a variable.
I have tried using the following in order to convert it into a raw file as another variable:
the r before to get the raw file path and that works but what happens if this file path is going to be change? Naturally I would need a variable
I have used the repr(file_path) and that works in some cases but when I try to use the os.listdir it doesnt!
I have tried the r'%s' %file_path as well but nothing
Im sure its something very simple so please let me know if someone has an answer for this!
Thank you!
**UPDATE
This is the code Im having problems with:
variable = '\\something.com\1400_somethingelse\1400_somethingyes\1400_Design\1500_sketch\ShotCam'
#Result:\something.com`0_somethingelse`0_somethingyes`0_Designh0_sketch\ShotCam
raw_path= repr(variable)
#Result:'\\something.com\x0somethingelse\x0somethingyes\x0Designh\x00_sketch\\ShotCam'
list_dir = os.listdir(raw_path)
print list_dir
#Result: # Error: WindowsError: file <maya console> line 8: 3 #
To make it a raw path I know I have to do:
variable = r'\\something.com\1400_somethingelse\1400_somethingyes\1400_Design\1500_sketch\ShotCam'
But I want this to become a variable so I can change it multiple times.
You can verify that your string is not a valid path by just printing it.
>>> '\\something.com\1400_somethingelse\1400_somethingyes\1400_Design\1500_sketch\ShotCam'
'\\something.com`0_somethingelse`0_somethingyes`0_Designh0_sketch\\ShotCam'
>>> r'\\something.com\1400_somethingelse\1400_somethingyes\1400_Design\1500_sketch\ShotCam'
'\\\\something.com\\1400_somethingelse\\1400_somethingyes\\1400_Design\\1500_sketch\\ShotCam'
use r to escape those \.
Here's my first simple test program in Python. Without importing the os library the program runs fine... Leading me to believe there's something wrong with my import statement, however this is the only way i ever see them written. Why am I still getting a syntax error?
import os # <-- why does this line give me a syntax error?!?!?! <unicode error> -->
CalibrationData = r'C:/Users/user/Desktop/blah Redesign/Data/attempts at data gathering/CalibrationData.txt'
File = open(CalibrationData, 'w')
File.write('Test')
File.close()
My end goal is to write a simple program that will look through a directory and tabularize data from relevant .ini files within it.
Well, as MDurant pointed out... I pasted in some unprintable character - probably when i entered the URL.
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.