0

I have a part in my program that requires working with directories.My current code is:

path = os.path.join('C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup')

Variable path prints: 'C:Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'.

My question is how can I make var path print 'C:Users/name/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'

Mark5352
  • 13
  • 3
  • 7
    Why do you want to though? On Windows, ``\`` is the directory separator, and the `os.path` module does the right thing here. – Thomas Aug 09 '17 at 10:58
  • yes it is correct only and replace does what you want.. – Mohideen bin Mohammed Aug 09 '17 at 10:59
  • Despite getting the "correct" output depending on your OS from `os.path.join` you probably also want to use [`os.path.realpath`](https://docs.python.org/3/library/os.path.html#os.path.realpath) on your `join`ed path to avoid an error from `c:Users` instead of `c:\Users`. – Christian König Aug 09 '17 at 11:09
  • @ChristianKönig Thank you,i didn't see there is a backslash missing after C: so I thought python uses / for directory operations. I always mix those. – Mark5352 Aug 09 '17 at 11:26
  • Look for the Path class in the [Unipath](https://github.com/mikeorr/Unipath) module. It has very nice features for this kind of problems – Franz Forstmayr Aug 09 '17 at 13:21

3 Answers3

1

As suggested in the comments the system does it.

You are better off changing os.sep or os.path.sep but however you can do this.

>>> os.path.sep = '\\'
>>> os.path.sep
'\\'              #we have changed the separator
>>> os.sep.join(['C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup'])
'C:\\Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'

But you can simply use this though,

>>> '\\'.join(['C:','Users',getpass.getuser(),'AppData','Roaming','Microsoft','Windows','Start Menu','Programs','Startup'])
'C:\\Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'

Well both are the same as mentioned in the comments!.

Also os.path.join does not depend upon os.sep or os.path.sep so changing them doesn't prove any effect.

void
  • 2,571
  • 2
  • 20
  • 35
0

Use the .replace() method of strings

"C:Users\\name\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup".replace('\\', '/')

#'C:Users/name/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup'
Clock Slave
  • 7,627
  • 15
  • 68
  • 109
0

You can replace '\\' with '/'

path = path.replace('\\','/')