invalid \x escape Module has no __module_name__ defined - python

when loading the following (or any python script for xchat version 2.8.9 on 64 bit windows 7):
__module_name__ = "test.py"
__module_version__ = "0.666"
__module_description__ = "I AM AN EXPERT PROGRAMMER"
import xchat, random, string, re
def test(word, word_eol, userdata):
cmd = word[1]
text = open("E:\\xpy\\nickslol.txt","r")
for line in text:
line = line.rstrip("\r\n")
xchat.command("%s %s" % (cmd, line))
xchat.hook_command("test", test)
[02:31:14] ValueError: invalid \x escape
[02:31:14] Module has no __module_name__ defined

Use raw strings for windows pathnames: r"E:\xpy\nickslol.txt"

It appears to be an error within xchat. The script works in the C drive, but not in subfolders.
IOError: [Errno 2] No such file or directory: 'C:\test\\startup.py'
Either the single or double backslash should not be there, depending on interpretation. They should definitely be consistent!

I recently came across this error. I'm far from an expert programmer, but I realized the problem is the \x in the string.
in python 2.7 (only version I tested)
x = 'C:\Users\xfolder\Desktop' # will give an "invalid \x escape"
x = 'C:\Users\\xfolder\Desktop' # will work properly (notice the stored value after)
I wish I could expand, but hopefully this is somewhat helpful.

Related

Python error: "cannot find path specified" [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 22 days ago.
import os
import random
os.chdir("C:\Users\Mainuser\Desktop\Lab6")
#Am i supposed to have a os.chdir?
# I think this is what's giving the error
#how do i fix this?
def getDictionary():
result = []
f = open("pocket-dic.txt","r")
for line in f:
result = result + [ line.strip() ];
return result
def makeText(dict, words=50):
length = len(dict)
for i in range(words):
num = random.randrange(0,length)
words = dict[num]
print word,
if (i+1) % 7 == 0:
print
Python gives me an error saying it cannot find the path specified, when i clearly have a folder on my desktop with that name. It might be the os.chidr?? what am i doing wrong?
Backslash is a special character in Python strings, as it is in many other languages. There are lots of alternatives to fix this, starting with doubling the backslash:
"C:\\Users\\Mainuser\\Desktop\\Lab6"
using a raw string:
r"C:\Users\Mainuser\Desktop\Lab6"
or using os.path.join to construct your path instead:
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")
os.path.join is the safest and most portable choice. As long as you have "c:" hardcoded in the path it's not really portable, but it's still the best practice and a good habit to develop.
With a tip of the hat to Python os.path.join on Windows for the correct way to produce c:\Users rather than c:Users.
Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:\Users\Mainuser\Desktop\Lab6" (note the r before the opening quote).

Error opening a csv file in python from a specific directory

I am very new to python and I am not having much experience in programming.
I try to open a CSV file from a specific directory and I get error.
import csv
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
Error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Study\\CEN\\Mini Project\\Data Sets\test.csv'
What to do ????
Use forward slashes:
ifile = open('F:/Study/CEN/Mini Project/Data Sets/test.csv', "rb");
Or at least escape your backslashes:
ifile = open('F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv', "rb");
Another option: use os.path.join:
out = os.path.abspath(os.path.join('path', 'test.csv'))
Your problem is here:
'F:\Study\CEN\Mini Project\Data Sets\test.csv'
^^
Because you did not use a raw string, Python thinks \t is supposed to mean a tab character.
You can see that in the error message, by the way: Notice how Python translated all the backslashes into double backslashes (which is how a literal backslash needs to be represented in a normal string) in all the places except the one where "backslash plus letter" actually meant something special?
Use
ifile = open(r'F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb")
(and remove the semicolons, you don't need them in Python) and it should work.
Your problem is with the "\t" AND a lack of exposure to various tools in the os.path package
The correct and easiest way to deal with this problem is to use os.path.normpath, combined with the string literal r, which ensures that backslashes are not interpreted as an escape character.
(Documentation on Lexical Analysis in python can be found here: https://docs.python.org/2/reference/lexical_analysis.html)
Open interactive python by typing "python" at the command line, and do the following to see that it's dead simple.
>>> import os
>>> path = r'F:\Study\CEN\Mini Project\Data Sets\test.csv'
>>> os.path.normpath(path)
'F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv'
normpath should be used when using hardcoded paths for scripts that may have to run on both dos and unix (eg OS X). It will ensure that the right kind of slashes are used for your particular environment
On a side note, if you are working with CSV files, you should use the petl library instead of the csv module. You'll save yourself a lot of time and hassle. Install it with pip install petl

Opening a file and matching Engr Label

1.Getting buildid from a buildlocation which is the last word after "\" which is "A1234ABCDE120083.1" in this case
2.After getting the buildid,am opening a file and then trying to match the line "Engr Label: Data_CRM_PL_177999" to get the label name which is "Data_CRM_PL_177999"
3.Final output should be "Data_CRM_PL_177999"
For some reason I am getting the following syntax error..
import re
Buildlocation= '\\umor\locations455\INT\A1234ABCDE120083.1'
Labelgetbuildlabel(Buildlocation)
def getbuildlabel(BuildLocation):
buildid=BuildLocation.split('\')[-1]
Notes=os.path.join(BuildLocation,Buildid + '_notes.txt')
if os.path.exists(Notes):
try:
open(Notes)
except IOError as er:
pass
else:
for i in Notes.splitlines:
if i.find(Engr Label)
label=i.split(:)[-1]
print label//output should be Data_CRM_PL_177999
Output should be:-
Line looks like below in the file
Engr Label: Data_CRM_PL_177999
SYNTAX ERROR
buildid=BuildLocation.split('\')[-1]
^
SyntaxError: EOL while scanning string literal
In the line
buildid=BuildLocation.split('\')[-1]
The backslash is actually escaping the following quotation mark
So, Python thinks this is actually your string:
'[-1])
Instead, you should do the following:
buildid=BuildLocation.split('\\')[-1]
And Python will interpret your string to be
\\
Interestingly, StackOverflow's syntax highlighter hints at this issue. If you look at your code, it treats everything after that first slash as part of the string, all the way to the end of your code sample.
You also have a few other issues in your code, so I tried cleaning it up a bit for you. (However, I don't have a copy of the file, so obviously, I wasn't able to test this)
import re
import os.path
build_location= r'\\umor\locations455\INT\A1234ABCDE120083.1'
label = get_build_label(build_location)
# Python prefers function and variable names to be all lowercase with
# underscore separating words.
def get_build_label(build_location):
build_id = build_location.split('\\')[-1]
notes_path = os.path.join(build_location, build_id + '_notes.txt')
# notes_path is the filename (a string)
try:
with open(notes_path) as notes:
# The 'with' keyword will automatically open and close
# the file for you
for line in notes:
if line.find('Engr Label'):
label = line.split(':')[-1]
return label
except IOError:
# No need to do 'os.path.exists' since notes_path doesn't
# exist, then the IOError exception will be raised.
pass
print label
The backslash is escaping the ' character (see the escape codes documentation)
Try this line instead:
buildid=BuildLocation.split('\\')[-1]
Now you have a backslash escaping the backslash, so your string is a literal backslash. The other thing you could do would be to tell Python that this string doesn't have any escape codes by prefixing it with an r like this:
buildid=BuildLocation.split(r'\')[-1]
You've got a number of other problems as well.
The comment character in Python is #, not //.
I think you're also confusing a filename with a file object.
Notes is the name of the file you're trying to open. Then, when you call open(Notes), you will get back a file object that you can read data from.
So you should probably replace:
open(Notes)
with
f = open(Notes)
And then replace:
for i in Notes.splitlines:
with
for line in f:
When you do a for loop over a file object, Python will automatically give you a line at a time.
Now you can check each line like this:
if line.find("Engr Label") != -1:
label = line.split(':')[-1]

Add an extra \ in python winpaths

Using python with windows I'm trying to get my program to see if Dropbox.exe exists if it doesn't nothing will happen if it does then the program will run. I used the print appdata as a debugging feature and this is what it prints: C:\Users\Me\AppData\Roaming
and I think the problem is that it needs to print C:\\Users\\me\\AppData\\Roaming\\ so then I can add the last part as \\Dropbox\\bin\\Dropbox.exe
import winpaths
appdata = winpaths.get_appdata()
print appdata
try:
with open('appdata\Dropbox\bin\Dropbox.exe') as f: pass
except IOError as e:
print 'dropbox cant be found'
First of all, you should use forward slashes for paths as backslashes are used to escape special characters, and forward slashes will work fine, even under windows. Alternatively, use raw strings (r"C:\some\path"). For an example of why you should do this:
>>> print("\path\to\random")
andom o
>>> print("/path/to/random")
/path/to/random
>>> print(r"\path\to\random")
\path\to\random
To do what you want, look at os.path.join() to join the two parts:
>>> import os
>>> os.path.join("/path/to", "some/file")
'/path/to/some/file'
Note that I am using Linux, so this produces a linux-style path, however, under Windows it will adjust accordingly.
So in your case:
with open(os.path.join(appdata, 'Dropbox/bin/Dropbox.exe')) as f:
...
You're likely to encounter bugs due to backslashes escaping characters in your string. Use a raw string to prevent this:
with open(r'appdata\Dropbox\bin\Dropbox.exe') as f:
Also, to add extra bits to pathnames, look at the os.path module, especially os.path.join.
You don't seem to be using the appdata variable in your open:
with open(appdata + r'\Dropbox\bin\Dropbox.exe') as f: pa

Using python 2.7, why does my unicode filename raise an IOError when calling file() on it?

Python 2.7:
I am trying to open an mp3 to read its ID3 tag using mutagen (so I'd rather not have to change the method), which calls:
file(filename, "rb")
For files with no special characters this works fine, but otherwise, I sometimes seem to get
IOError: [Errno 2] No such file or directory: u"somepath\\08 - Muse - I Belong To You - Mon C\x9cur S'ouvre \xc0 Ta Voix.mp3"
while other times
u"somepath\\02 - Max\xefmo Park - Apply Some Pressure.mp3"
works fine.
What's the difference between the two? Why does one work while the other doesn't?
Cheers,
Felix
EDIT: It worked when running under pydev in Eclipse, for which
sys.getdefaultencoding()
returned "Cp1252" but not from the command line which returned "ascii". The filename when printed to the Eclipse console was
u"somepath\\08 - Muse - I Belong To You - Mon C\u0153ur S'ouvre \xc0 Ta Voix.mp3"
EDIT: The code which gets the filename from Winamp (the music player) is:
winampProcess = win32api.OpenProcess(win32con.PROCESS_VM_READ, False, processID)
memoryBuffer = ctypes.create_string_buffer(256)
ctypes.windll.kernel32.ReadProcessMemory(winampProcess.handle, memoryPointer, memoryBuffer, 256, 0)
winampProcess.Close()
rawPath = win32api.GetFullPathName(memoryBuffer.raw.split("\x00")[0])
try:
unicodeString = unicode(rawPath)
except UnicodeDecodeError:
unicodeString = u""
for char in rawPath:
try:
unicodeString += unicode(char)
except UnicodeDecodeError as err:
errStr = str(err)
startIndex = errStr.index("0x")
endIndex = errStr.index(" ", startIndex)
hexStr = ""
for i in range(startIndex, endIndex):
hexStr += errStr[i]
unicodeString += unichr(int(hexStr, 16))
return unicodeString
EDIT: The problem is fixed if I explicitly set
unicode(str, "cp1252")
but I still don't understand what causes the problem, and this is a hacky fix that probably won't work for other dodgy filenames...
Just guessing - you're pulling the filename from a program which is using a multibyte character set in the current default encoding, which is cp1252 for English versions of Windows. Ascii doesn't include any extended characters, which is why you get the error when you try to encode the string into Unicode using the Ascii encoding.
Edit: this answer has some information about encoding file names in the current Windows code page.
Use os.listdir() on the directory to see what the filename is, encoded. Then compare that to what you get when you do filename.encode('cp1252'). There should be a difference, and that should tell you what is wrong.
The only real problem I can think of is that something gets decoded twice. You could have normalization problems too, but that seems unlikely in this case.

Categories