0

I have a python script running in windows that detects the user profile using os.environ['UserProfile']. I need to amend this path in order to perform some operations.

For example. I read in:

C:\Users\User\Desktop

and need to create:

C':\'Users'\'User'\'Desktop

basically surrounding all non-letters and non-numbers with single quotes.

I'm wondering if there's a best, most general way to do this. re? split? os.join? Ideally, I want to do it with full generality, independent of path name or os.

Here's my current clunky code to achieve it:

for letter in amend_dir:
    if amend_dir[track] not in string.ascii_letters:
        if amend_dir[track-1] in string.ascii_letters:
            if amend_dir[track+1] not in string.ascii_letters:
                newer_letter = "'"+letter
    if amend_dir[track] not in string.ascii_letters:
        if amend_dir[track-1] not in string.ascii_letters:
            if amend_dir[track+1] in string.ascii_letters:
                newer_letter = letter+"'"
    if amend_dir[track] not in string.ascii_letters:
        if amend_dir[track-1] in string.ascii_letters:
            if amend_dir[track+1] in string.ascii_letters:
                    newer_letter = "'"+letter+"'"

EDIT:

I didn't have much luck with the os module, but this 2-liner works nicely:

amend_dir = (parameters['default_dir'].replace('\',"'\'")) amend2_dir = (amend_dir.replace(":'\'", "':\'"))

The_Glidd
  • 75
  • 3
  • 8

2 Answers2

1

There are already generalised pathname manipulation tools aplenty in the standard module os.path just use that.

Remember that windows is unusual in the use of \ and L: notations the os.path modules handle this cleanly for you.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
0

how about something like this:

import re
x = r'C:\Users\User\Desktop'
re.sub(r'([^\w]+)',"'\g<1>'",x)
lev
  • 3,986
  • 4
  • 33
  • 46