file reading / reference issue in python - python

Recently I have referenced a file in my desktop using python 3.4 64bit GUI application. The problem I have got is as follows:
The code I tried is :
fo=open("c:\users\Ismail Nuru\Sesktop\myfile\lab.txt","r+")
string1=fo.read()
print(string1)
fo.close()

Python is trying to use the \uXXXX part of your string as a unicode escape sequence.
To fix this, you have 3 options here:
Use a raw string r'C:\users\Ismail Nuru\Sesktop\myfile\lab.txt'
Double the backslashes 'C:\\users\\Ismail Nuru\\Sesktop\\myfile\\lab.txt'
Or use forward slashes 'C:/users/Ismail Nuru/Sesktop/myfile/lab.txt')

Related

How to make python 3 understand double backslash? [duplicate]

This question already has answers here:
How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?
(2 answers)
Closed 1 year ago.
So, as SO keeps suggesting me, I do not want to replace double backslashes, I want python to understand them.
I need to copy files from a windows distant directory to my local machine.
For example, a "equivalent" (even if not) in shell (with windows paths):
cp \\directory\subdirectory\file ./mylocalfile
But python does not even understand double backslashes in strings:
source = "\\dir\subdir\file"
print(source)
$ python __main__.py
__main__.py:1: DeprecationWarning: invalid escape sequence \s
source = "\\dir\subdir\file"
\dir\subdir
ile
Is Python able to understand windows paths (with double backslashes) in order to perform file copies ?
You can try this also:
source = r"\dir\subdir\file"
print(source)
# \dir\subdir\file
You can solve this issue by using this raw string also.
What we are doing here is making "\dir\subdir\file" to raw string by using r at first.
You can visit here for some other information.
raw strings are raw string literals that treat backslash (\ ) as a literal character. For example, if we try to print a string with a “\n” inside, it will add one line break. But if we mark it as a raw string, it will simply print out the “\n” as a normal character.

GhPython vs Python: TypeErrorException from GH but not from Shell

I am using a library called py_openshowvar to communicate with a Kuka robot arm from grasshopper.
Everything works fine if I run the program from a command line python shell. However, when I run the same thing from GhPython, I get the following:
Not sure why I get the exceptions with GhPython but not when I run it outside the GH environment. The program still connects to the server and retrieves/sends the info I need, but I want to make sure and address this exception.
Thanks!
It is hard to tell you how to fix the error as you do not provide the code that triggers it, but in substance it comes from the fact that GHPython is IronPython (an implementation of Python based on .Net) whereas Python Shell is an implementation written in C.
The two implementations are similar but you sometimes hit a difference.
In your case the script is expecting a string or tuple but gets an IronPython.Runtime.Bytes.
Hmm, got bytes when expecting str looks like a unicode string vs byte string problem. You do no describe what are the versions of your CPython and GHPython, but you should know that Python 2 strings are byte strings while Python 3 ones are unicode strings.
If in Python 2 you can force a litteral string to be unicode by prepending it with u: u"foo" is a unicode string. You can also decode a byte string to its unicode version: b'ae\xe9\xe8'.decode('Latin1') is the unicode string u'aeéè'

I want to call my bingo.sh file through python in mac how to do that?

os.system('sh ~/scripts/bingo.sh')
this gives an error of Non ascii characters.
import subprocess
subprocess.call(["sh","/full/path/bingo.sh"])
"Python 2 uses ascii as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses utf-8 as the default encoding for source files, so this is less of an issue"
I was able to find this by googling "Python error 'Non ascii characters'"
From my understanding this is a good answer
How to make the python interpreter correctly handle non-ASCII characters in string operations?
hope this helps
(I am new to coding and was looking into this to help my own understanding of how to avoid this problem for myself. Take what I have to say with a grain of salt.)

Delete folders which contains special chars in Python

I have some folders which names contains special chars.
I tried to remove them like this:
shutil.rmtree(os.path.join(mypath,"Input"))
and I get an error:
The filename, directory name, or volume label syntax is incorrect:
...\library elements ???? ?????
and my Folder name is :
library elements 階段要素 Элементы
How can I delete this folder?
Thanks David
Assuming you're on Python 2.x, this appears to be a known bug in Python 2.7. It's likely a problem with locale handling when using the ANSI APIs on Windows (Unicode and locale handling was much weaker in the 2.x line).
Assuming you can't switch to Python 3.x, try passing the path as a unicode path, rather than str, so it exercises the Windows Unicode APIs (that will handle the non-ASCII names correctly). Since your base path appears to be an ASCII str, this can be done by changing:
shutil.rmtree(os.path.join(mypath,"Input"))
to:
shutil.rmtree(os.path.join(mypath,"Input").decode('ascii'))

SyntaxError when trying to use backslash for Windows file path [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 7 months ago.
I tried to confirm if a file exists using the following line of code:
os.path.isfile()
But I noticed if back slash is used by copy&paste from Windows OS:
os.path.isfile("C:\Users\xxx\Desktop\xxx")
I got a syntax error: (unicode error) etc etc etc.
When forward slash is used:
os.path.isfile("C:/Users/xxx/Desktop/xxx")
It worked.
Can I please ask why this happened? Even the answer is as simple as :"It is a convention."
Backslash is the escape symbol. This should work:
os.path.isfile("C:\\Users\\xxx\\Desktop\\xxx")
This works because you escape the escape symbol, and Python passes it as this literal:
"C:\Users\xxx\Desktop\xxx"
But it's better practice and ensures cross-platform compatibility to collect your path segments (perhaps conditionally, based on the platform) like this and use os.path.join
path_segments = ['/', 'Users', 'xxx', 'Desktop', 'xxx']
os.path.isfile(os.path.join(*path_segments))
Should return True for your case.
Because backslashes are escapes in Python. Specifically, you get a Unicode error because the \U escape means "Unicode character here; next 8 characters are a 32-bit hexadecimal codepoint."
If you use a raw string, which treats backslashes as themselves, it should work:
os.path.isfile(r"C:\Users\xxx\Desktop\xxx")
You get the problem with the 2 character sequences \x and \U -- which are python escape codes. They tell python to interpret the data that comes after them in a special way (The former inserts bytes and the latter unicode). You can get around it by using a "raw" string:
os.path.isfile(r"C:\Users\xxx\Desktop\xxx")
or by using forward slashes (as, IIRC, windows will accept either one).

Categories