faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 6 people (50%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

os.path.split() with DOS path names

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 16, Fredrik Lundh


"""
Packages: operating_systems.dos
"""

"""
>A Python CGI script gets a DOS path name like "c:\blabla\this_os.sux".
>I need to extract the basename from string however os.path.basename()
>and os.path.split() return bad results for non-POSIX filenames:
>
>>>> os.path.split('c:\blabla\this_os.sux')
>('', 'c:\\blabla\\this_os.sux')
>>>> os.path.basename('c:\blabla\this_os.sux')
>'c:\010labla\011his_os.sux'

Well, they work just fine if you send them valid DOS
filenames.  But you don't:
"""

print repr('c:\blabla\this_os.sux')
# 'c:\010labla\011his_os.sux'

"""
When Python parses the constant string, '\b' gets converted
to a backspace, and '\t' to a tab.  To actually get a backslash
into the string, either use the "r" prefix to switch off back-
slash handling:
"""

print r'c:\blabla\this_os.sux'
# c:\blabla\this_os.sux

"""
or escape the backslashes:
"""

print 'c:\\blabla\\this_os.sux'
# c:\blabla\this_os.sux