[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [code] [pygame] OT - getting file name from path string



To "tell" Python you are looking for a backslash, you need to escape it, e.g. "\\".

s = r'c:\temp'
for c in s:
...     if c == '\\':
...             print 'Slash ', c
...     else:
...             print 'Not slash ', c
...
Not slash  c
Not slash  :
Slash  \
Not slash  t
Not slash  e
Not slash  m
Not slash  p

That being said, as Rikard has already pointed out, use the os.path module for all mucking about with paths. If you are a C/C++ programmer coming to Python, check out the Python Standard Library; most tedious stuff you have to write in other languages (like parsing a path) has already been done and tested. This is one of the best things about Python: most of the boring code has already been done, letting you focus on the fun stuff.

Cheers,
Taylor


----- Original Message ----- From: "altern" <altern2@xxxxxxxxx>
To: <pygame-users@xxxxxxxx>
Sent: Thursday, June 29, 2006 12:53 PM
Subject: [code] [pygame] OT - getting file name from path string



hi

I know this is OT but ...
i need to get the name of a file from the string containing the path. I did some ugly code (i guess it can be done nicely with regular expressions but i dont know much about it.) and i am almost there, the problem is that because the path contains \ backslashes i dont know how to check if the char is a \


this is the (ugly) code:

p = 'c:\file\myfile.gif'
start = 0
for c in range(len(p)-1, -1, -1): // read starting from end
if start :
if p[c] == '\' : # << THIS iS THE PROBLEM
print '+'*10
while 1: pass
else :
s = s + p[c] ## append
print s
else :
if p[c] == '.' : # already read the extension start getting the chars into s
start = 1




Basically when it comes to check if I reached the \ i dont know how to tell python i am looking for a character "\" as this is the scape character used in strings. I have been looking for tips online but couldnt get anything clear.

many thanks

enrike