Reputation: 11
dir = "C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
print dir
using the code above, i get this... i know that \t is tab
C:\Users\Geraldes\Desktop\media (espacamento) este\ASMS_TapeA01A1691329.mxf
but, to fix this i do:
dir1 = dir.replace("\\", "\\\\")
print "dir:",dir1
and i get
C:\\Users\\Geraldes\\Desktop\\media (espacamento) este\\ASMS_TapeA01A1691329.mxf
how can i fix this problem?
Upvotes: 0
Views: 236
Reputation: 146
A less obvious and less efficient way is to do the following:
import os
os.chdir()#change to each directory separately
print os.getcwd()
Upvotes: 0
Reputation: 85613
Nobody said but, in addition to expanded backlashes and raw strings, you can also use forward slashes
>>> dir = "C:/Users/Geraldes/Desktop/media/teste/ASMS_TapeA01A1691329.mxf"
>>> dir
'C:/Users/Geraldes/Desktop/media/teste/ASMS_TapeA01A1691329.mxf'
>>>
In fact, forward slashes are accepted by Windows (Check this for more info)
Microsoft Windows [Versión 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Reservados todos los derechos.
C:\>cd Users/joaquin
C:\Users\joaquin>
In any case the safest method is to use os.path.join
to build your paths in an OS agnostic way.
>>> import os
>>> os.path.join('C:\Users', 'Geraldes', 'Desktop', 'media', 'teste', 'ASMS.mxf')
'C:\\Users\\Geraldes\\Desktop\\media\\teste\\ASMS.mxf'
>>>
Upvotes: 4
Reputation: 238131
You can use raw formatting:
dir = r"C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
This will print as:
>>> print(dir)
C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf
Upvotes: 3
Reputation: 816364
Define a "raw" string:
dir = r"C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
Upvotes: 3
Reputation: 12819
escape your original string's backslashes, or use raw strings.
That is,
dir = "C:\\Users\\Geraldes\\Desktop\\media\\teste\\ASMS_TapeA01A1691329.mxf"
or
dir = r"C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
BUT: be careful with the second choice, because raw strings were not invented for windows paths - they were put there for regular expressions. Thus, one day you will find that you want to put a backslash at the end of the string, like this:
dir = "C:\Users\Geraldes\Desktop\media\teste\"
It won't work. This is discussed in greater depth here.
Upvotes: 5