Reputation: 379
I have a string like script = "C:\Users\dell\byteyears.py"
. I wanna put the string "Python27\"
in between the string like script = "C:\Users\dell\Python27\byteyears.py
. Why I need is because build_scripts is not running correctly on the windows. Anyway, how can I do this wish in time efficient way ?
EDIT : I will not print anything. String is stored on the script variable in the build_scripts
script = convert_path(script)
I should put something to convert it, like
script = convert_path(script.something("Python27/"))
The question is that what something
should be.
Upvotes: 0
Views: 86
Reputation: 4903
os.path
is best for dealing with paths, also forward slashes are ok to use in Python.
In [714]: script = r"C:/Users/dell/byteyears.py"
In [715]: head, tail = os.path.split(script)
In [716]: os.path.join(head, 'Python27', tail)
Out[716]: 'C:/Users/dell/Python27/byteyears.py'
in a module.
import os
script = r"C:/Users/dell/byteyears.py"
head, tail = os.path.split(script)
newpath = os.path.join(head, 'Python27', tail)
print newpath
gives
'C:/Users/dell/Python27/byteyears.py'
internally Python is in general agnostic about the slashes, so use forward slashes "/" as they look nicer and save having to escape.
Upvotes: 2
Reputation: 23490
Try:
from os.path import abspath
script = "C:\\Users\\dell\\byteyears.py"
script = abspath(script.replace('dell\\', 'dell\\Python27\\'))
And if you're mixing / and \ then you'd better use abspath() to correct it to your platform!
Other ways:
print "C:\\Users\\dell\\%s\\byteyears.py" % "Python27"
or if you want the path to be more dynamic, this way you can pass a empty string:
print "C:\\Users\\dell%s\\byeyears.py" % "\\Python27"
Also possible:
x = "C:\\Users\\dell%s\\byeyears.py"
print x
x = x % "\\Python27"
print x
Upvotes: 0
Reputation: 174662
import os
os.path.join(script[:script.rfind('\\')],'Python27',script[script.rfind('\\'):])
Upvotes: 1