File location is changed? - python

Using pygame (from pygame import *) I tried to load a picture, but this happened:
Traceback (most recent call last):
File "C:/Users/Ben/Documents/Python Files/Rocket game with things", line 15, in <module>
right_fin = image.load('C:\Users\Ben\Pictures\right.png').convert()
error: Couldn't open C:\Users\Ben\Picturesight.png
There was basicly no code before this, so im not going to post it. I haven't encounted this before, nor have any idea what the problem even is. Sorry if the answer's obvious.

Backslashes have special meaning in Python strings, and \r is the escape code for a carriage return character.
Use double slashes, forward slashes or r'' raw strings (which do not interpret backslashes as escape sequences) to define the path:
right_fin = image.load('C:\\Users\\Ben\\Pictures\\right.png').convert()
right_fin = image.load('C:/Users/Ben/Pictures/right.png').convert()
right_fin = image.load(r'C:\Users\Ben\Pictures\right.png').convert()

Related

"No such file or directory" error with both file in same directory AND when using absolute path

all. I'm running into a "no such file or directory" issue in python that's stumped me.
Things I've tried so far:
Closing any program that I could think might have the file open
Having the file in the same directory as the program I'm running
Using the absolute path name
Escaping the backslashes
Escaping the backslashes and spaces
Changing the backslashes to forward slashes
Removing all spaces, special symbols, and numbers from the filename
I even checked with os.getcwd and os.path.abspath and copy-pasted the path exactly.
I'm not sure what's going on here. I'm at a loss now. Would I get this same error if the file is still open in some elusive background program?
This is the relevant bit of code:
print(os.getcwd())
print(os.path.abspath('RainyGenki.json'))
deckName = "C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki.json"
deck = open(deckName, 'r') #opens card deck
This is the error message:
C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag
C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki.json
Traceback (most recent call last):
File "C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\kanji_drag\kanji_main.py", line 79, in <module>
deck = open(deckName, 'r') #opens card deck
IOError: [Errno 2] No such file or directory: 'C:\\Users\\myName\\My Documents\\LiClipse Workspace\\KanjiDrag\\RainyGenki.json'
Using a raw string...
If you are sure that your path is OK then use the python syntax for a raw string:
In plain English: String literals can be enclosed in matching single
quotes (') or double quotes ("). They can also be enclosed in matching
groups of three single or double quotes (these are generally referred
to as triple-quoted strings). The backslash () character is used to
escape characters that otherwise have a special meaning, such as
newline, backslash itself, or the quote character. String literals may
optionally be prefixed with a letter 'r' or 'R'; such strings are
called raw strings and use different rules for interpreting backslash
escape sequences. A prefix of 'u' or 'U' makes the string a Unicode
string. Unicode strings use the Unicode character set as defined by
the Unicode Consortium and ISO 10646. Some additional escape
sequences, described below, are available in Unicode strings. A prefix
of 'b' or 'B' is ignored in Python 2; it indicates that the literal
should become a bytes literal in Python 3 (e.g. when code is
automatically converted with 2to3). A 'u' or 'b' prefix may be
followed by an 'r' prefix.
This basically means that to escape the backslash escape sequences, you just need to put an 'r'before the string like:
deckName = r"C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki.json"
ck = open(deckName, "r")
And even though you say you have tried it, escaping the backslashes should also work:
deckName = "C:\\Users\\myName\\My Documents\\LiClipse Workspace\\KanjiDrag\\RainyGenki.json"
ck = open(deckName, "r")
I had a folder called KanjiDrag, and within that I had the actual source folder kanji_drag which is where the json file and the main module were. The path I was using was accessing the KanjiDrag folder, but not the kanji_drag folder, and I didn't catch the different names. This is my dumbest file IO mistake yet. Thanks for all the replies, many of which I'll still refer to later when I refine this part of my program.

Error Encoding non-BMP characters

I've developed a little program in python 3.4, but when I try to run it, at the end says:
File "C:\Python34\lib\idlelib\PyShell.py", line 1352, in write
return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 39559-39559: Non-BMP character not supported in Tk
I've tried all, but I found nothing. Help, please!
I presume you did the equivalent of the following.
>>> print('\U00011111')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print('\U00011111')
File "C:\Programs\Python34\lib\idlelib\PyShell.py", line 1347, in write
return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode character '\U00011111' in position 0: Non-BMP character not supported in Tk
The problem is as stated: Idle uses the tkinter interface to tcl/tk and tk cannot display non-BMP supplementary chars (ord(char) > 0xFFFF).
Saving a string with non-BMP chars to a file will work fine as long as you encode with utf-8 (or -16, or -32).
On Windows, the console interpreter gives the same error with 'UCS-2' replaced by 'charmap'. The console interpreter is actually worse in that it raises an error even for some BMP chars, depending on the code page being used. I do not know what the situation is on other systems.
EDIT
I forget the best alternative, at least on Windows. Either of the following will print any string on any ascii terminal.
>>> repr('\U00011111')
"'\U00011111'"
>>> ascii('\U00011111')
"'\\U00011111'"
repr() does not double backslashes when echoed, ascii() does. These escape more chars than needed for Idle, but will not raise an exception at the >>> prompt. However, for reasons I do not understand, print(repr('\U00011111')) fails, so print(ascii(s)) is needed within a program to print s.

Can't handle strings in windows

I have written a python 2.7 code in linux and it worked fine.
It uses
os.listdir(os.getcwd())
to read folder names as variables and uses them later in some parts.
In linux I used simple conversion trick to manually convert the non asci characters into asci ones.
str(str(tfile)[0:-4]).replace('\xc4\xb0', 'I').replace("\xc4\x9e", 'G').replace("\xc3\x9c", 'U').replace("\xc3\x87", 'C').replace("\xc3\x96", 'O').replace("\xc5\x9e", 'S') ,str(line.split(";")[0]).replace(" ", "").rjust(13, "0"),a))
This approach failed in windows. I tried
udata = str(str(str(tfile)[0:-4])).decode("UTF-8")
asci = udata.encode("ascii","ignore")
Which also failed with following
DEMĀ¦-RTEPE # at this string error occured
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Users\benhur.satir\workspace\Soykan\tkinter.py", line 178, in SparisDerle
udata = str(str(str(tfile)[0:-4])).decode("utf=8")
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa6 in position 3: invalid start byte
How can I handle such characters in windows?
NOTE:Leaving them UTF causes xlswriter module to fail, so I need to convert them to asci. Missing characters are not desirable yet acceptable.
Windows does not like UTF8. You probably get the folder names in the default system encoding, generally win1252 (a variant of ISO-8859-1).
That's the reason why you could not find UTF8 characters in the file names. By the way the exception says you found a character of code 0xa6, which in win1252 encoding would be |.
It does not say exactly what is the encoding on your windows system as it may depends on the localization, but it proves the data is not UTF8 encoded.
How about this?
You can use this for optional .replace()
In the module of string, there is a set of characters that can be used..
>>> import string
>>> string.digits+string.punctuation
'0123456789!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
>>>

Problem opening a text file in Python

This seems like it should be very easy:
f = open('C:\Users\john\Desktop\text.txt', 'r')
But I am getting this error:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
f = open('C:\Users\john\Desktop\text.txt', 'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\robejohn\\Desktop\text.txt'
Any thoughts?
Your file name has backslash characters in it. Backslash is the escape character in Python strings. Either replace them with '/' characters or use r'C:\Users\john\Desktop\text.txt'.
You might also find the functions in os.path useful.
In Windows, paths use backslash. But if a string that must represent a path contains characters such as '\r' , '\t' , '\n' .... etc there will be this kind of problem. This is the precise reason why your string fails to represent a path.
In the absence of these problematic characters, there will be no problem. If they are present, you must escape the backslashes or use a raw string r'C:\Users\john\Desktop\text.txt'

How to replace all '0xa0' chars with a ' ' in a bunch of text files?

i've been trying to mass-edit a bunch of text files to utf-8 in python and this error keeps popping out. is there a way to replace them in some python scrips or bash commands?
i used the code:
writer = codecs.open(os.path.join(wrd, 'dict.en'), 'wtr', 'utf-8')
for infile in glob.glob(os.path.join(wrd,'*.txt')):
print infile
for line in open(infile):
writer.write(line.encode('utf-8'))
and got these sorts of errors:
Traceback (most recent call last):
File "dicting.py", line 30, in <module>
writer.write(line2.encode('utf-8'))
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 216: unexpected code byte
OK, first point: your output file is set to automatically encode text written to it as utf-8, so don't include an explicit encode('utf-8') method call when passing arguments to the write() method.
So the first thing to try is to simply use the following in your inner loop:
writer.write(line)
If that doesn't work, then the problem is almost certainly the fact that, as others have noted, you aren't decoding your input file properly.
Taking a wild guess and assuming that your input files are encoded in cp1252, you could try as a quick test the following in the inner loop:
for line in codecs.open(infile, 'r', 'cp1252'):
writer.write(line)
Minor point: 'wtr' is a nonsensical mode string (as write access implies read access). Simplify it to either 'wt' or even just 'w'.
Did you omit some code there? You're reading into line but trying to re-encode line2.
In any case, you're going to have to tell Python what encoding the input file is; if you don't know, then you'll have to open it raw and perform substitutions without help of a codec.
Please be serious - a simple replace() operation will do the job:
line = line.replace(chr(0xa0), '')
In addition the codecs.open() constructors support the 'errors' parameter to handle
conversion errors. Please read up (yourself).

Categories

Resources