if statement to identify directory path [duplicate] - python

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 15 days ago.
I've got watchdog and pyaudio playing together so if either of two directories is modified I hear a sound.
Now I'm trying to get a different sound for each directory. Watchdog can print the path that triggered it, so I'm trying to use that difference to fire each sound.
def on_modified(self, event,):
x = event.src_path
print(x)
if x == 'c:/WATCHDOGTEST\x.csv':
pyaudio_01.PLAY_SOUND()
if x == 'c:/WATCHDOGTEST2\x.csv':
pyaudio_02.PLAY_SOUND()
The print(x) works fine:
c:/WATCHDOGTEST2\x.csv
however - the if statement won't work - I get:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \xXX escape
Any ideas appreciated!

Using \x in the string, python interprets anything after \x as hexadecimal charector, so you need to escape this charector, using one more slash.
So your value will be c:/WATCHDOGTEST\\x.csv
Or you can turn it into raw string using r formater, r'c:/WATCHDOGTEST\x.csv', this is the best way, beacuse it automatically ignores any special charectory if present.

OK just figured it out - I added a forward slash to the target directory to get rid of the backslash it added itself, now it works. Doh.

using built-in library pathlib would be more easy.
PureWindowsPath('c:/Program Files/').match(event.src_path)
Pure path objects provide path-handling operations which don’t actually access a filesystem. There are three ways to access these classes, which we also call flavours.

Related

re.escape returns unusable directory

using re.escape() on this directory:
C:\Users\admin\code
Should theoratically return this, right?
C:\\Users\\admin\\code
However, what I actually get is this:
C\:\\Users\\admin\\code
Notice the backslash immediately after C. This makes the string unusable, and trying to use directory.replace('\', '') just bugs out Python because it can't deal with a single backslash string, and treats everything after it as string.
Any ideas?
Update
This was a dumb question :p
No it should not. It's help says "Escape all the characters in pattern except ASCII letters, numbers and '_'"
What you are reporting you are getting is after calling the print function on the resulting string. In console, if you type directory and press enter, it would give something like: C\\:\\\\Users\\\\admin\\\\code. When using directory.replace('\\','') it would replace all backslashes. For example: directory.replace('\\','x') gives Cx:xxUsersxxadminxxcode. What might work in this case is replacing both the backslash and colon with ':' i.e. directory.replace('\\:',':'). This will work.
However, I will suggest doing something else. A neat way to work with Windows directories in Python is to use forward slash. Python and the OS will work out a way to understand your paths with forward slashes. Further, if you aren't using absolute paths, as far as the paths are concerned, your code will be portable to Unix-style OSes.
It also seems to me that you are calling re.escape unnecessarily. If the printing the directory is giving you C:\Users\admin\code then it's a perfectly fine directory to use already. And you don't need to escape it. It's already done. If it wasn't escaped print('C:\Users\admin\code') would give something like C:\Usersdmin\code since \a has special meaning (beep).

Python IDLE is glitching when I try to load images with pygame

I don't know how to explain this so I have included a video showing you what's happening.
https://www.youtube.com/watch?v=XCNl24mpko0&feature=youtu.be
Notice how it says it's trying to load "imagesed shield.png" This is because the baskslash is escaping "r". Putting an "r" at the front will fix it by converting the string to a raw string, as will replacing the backslash with a forward slash, or escaping the backslash itself.
red_shield = pyg.image.load(r'images\red shield.png')
red_shield2 = pyg.image.load('images/red shield.png')
red_shield3 = pyg.image.load('images\\red shield.png')
Edit: I suppose I should mention that I assume this is due to IDLE trying to represent a break character (\r is a break character, hence the answer). I don't really know if it's a real issue in the grand scheme of things.

Set "hide" attribute on folders in windows OS?

Trying to hide folder without success. I've found this :
import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)
but it did not work for me. What am I doing wrong?
There are two things wrong with your code, both having to do with the folder name literal. The SetFileAttributesW() function requires a Unicode string argument. You can specify one of those by prefixing a string with the character u. Secondly, any literal backslash characters in the string will have to be doubled or you could [also] add an r prefix to it. A dual prefix is used in the code immediately below.
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
ret = ctypes.windll.kernel32.SetFileAttributesW(ur'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
if ret:
print('attribute set to Hidden')
else: # return code of zero indicates failure -- raise a Windows error
raise ctypes.WinError()
You can find Windows' system error codes here. To see the results of the attribute change in Explorer, make sure its "Show hidden files" option isn't enabled.
To illustrate what #Eryk Sun said in a comment about arranging for the conversion to Unicode from byte strings to happen automatically, you would need to perform the following assignment before calling the function to specify the proper conversion of its arguments. #Eryk Sun also has an explanation for why this isn't the default for pointers-to-strings in the W versions of the WinAPI functions -- see the comments.
ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32)
Then, after doing that, the following will work (note that an r prefix is still required due to the backslashes):
ret = ctypes.windll.kernel32.SetFileAttributesW(r'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
Try this code:
import os
os.system("attrib +h " + "your file name")

Repeated errors while working with Portable Python [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
Note: This was not answered by the question that was marked as the original. This is more than just a Python v2 vs v3 problem, which I explain in the comments below.
Original post:
I am trying to learn Python at work, so I am currently using Portable Python 3.2.1.1 (which will henceforth be referred to as PP). (I mention this because this problem doesn't happen at home when I use my Mac and regular Python.)
I am working through exercise 16 of Learning Python the Hard Way (http://learnpythonthehardway.org/book/ex16.html). I've heard this isn't the best learning tool, but I am a complete programming n00b and I'm a hands-on learner. If you have any better suggestions, I'm open!
The first few lines of the exercise read:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
My script is titled Ex16.py and the file I am using is Python.txt, and both of these are in the same folder as the PP .exes. I don't think that's necessary, but hoped maybe it would fix the problem... negative. When I press "Run" in PP, it doesn't work because argv requires you provide an argument when you start the script: python Ex16.py Python.txt
When I launch Python.exe (which, in PP is Portable-Python.exe), I get the standard Python prompt, >>>, but whatever I enter I get the same error message:
File "<stdin>", line 1
with whatever I've just tried repeated back to me with the marker to
indicate where the problem is. (has not been helpful so far)
SyntaxError: invalid syntax
I have tried typing the following at the >>> prompt:
python Ex16.py Python.txt,,
Ex16.py Python.txt,,
"%PATH&\Ex16.py" "%PATH%\Python.txt" (with the actual filepaths),,
print 'hello world'
I just keep getting the same invalid syntax error over and over. Even a basic print command returned an invalid syntax error. The only one that triggered a different error was the one where I tried whole filepaths. That one returned:
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape
Yes, I have Googled the crap outta both errors. I read that sometimes the problem is not doubling the backspaces, so I tried that, too, putting two \ where just one had been before in both filepaths. I even tried putting — # -*- coding: utf-8 -*- at the beginning of the script thinking maybe there was some unicode error. That, with the full filepaths, resulted in the same unicode error mentioned earlier.
Yes, I have checked that my code is matching that in the exercise.
Yes, this works at home on non-PP.
All this leads me to believe that the problem is probably in the way I'm trying to run the scripts in PP (but why won't print work?), but I haven't a clue what I'm doing wrong.
Thanks!
print is a function in Python 3:
print('my string with content and the like')
It is no longer supported as being a 'statement'. You might want to check out a list of things that changed from python2.x to python3.x (there's a number of incompatibilities). Also, you might be better off finding a tutorial using Python3.
You have to type:
Portable-Python.exe Ex16.py Python.txt
at your command prompt. To get a command prompt, press WindowsKey-R, then type "cmd" and press enter. You should now be looking at something like c:\>. Navigate to your portable python installation by using the cd command.

How to append '\\?\' to the front of a file path in Python

I'm trying to work with some long file paths (Windows) in Python and have come across some problems. After reading the question here, it looks as though I need to append '\\?\' to the front of my long file paths in order to use them with os.stat(filepath). The problem I'm having is that I can't create a string in Python that ends in a backslash. The question here points out that you can't even end strings in Python with a single '\' character.
Is there anything in any of the Python standard libraries or anywhere else that lets you simply append '\\?\' to the front of a file path you already have? Or is there any other work around for working with long file paths in Windows with Python? It seems like such a simple thing to do, but I can't figure it out for the life of me.
"\\\\?\\" should give you exactly the string you want.
Longer answer: of course you can end a string in Python with a backslash. You just can't do so when it's a "raw" string (one prefixed with an 'r'). Which you usually use for strings that contains (lots of) backslashes (to avoid the infamous "leaning toothpick" syndrome ;-))
Even with a raw string, you can end in a backslash with:
>>> print r'\\?\D:\Blah' + '\\'
\\?\D:\Blah\
or even:
>>> print r'\\?\D:\Blah' '\\'
\\?\D:\Blah\
since Python concatenates to literal strings into one.

Categories

Resources