简体   繁体   中英

Python escape character when parameter is a path - Windows

I am relatively new to python, and I am writing a method for a toolbox I am creating.

The function is something like this:

def explodeByUniqueAttributeValue(inputfile,fieldname,outputworkspace):
...

When the path of the input file or the workspace have specific escape characters such as \\t the function does not work. More specifically the input file might be something like this:

"C:\tmp\Data\Data.dbf"    

and the outputworkspace might be something like this:

"D:\Data\2010_12\Output"

In these cases what python reads is accordingly:

>>> inputfile    
C:\tmp\\Data\\Data.dbf   

>>> print inputfile    
C:  mp\Data\Data.dbf

and

>>> outputworkspace  
'D:\\Data\x810_12\\Output'   
>>> print outputworkspace
D:\Dataチ0_12\Output

My Question is:
Is there any way to parse the input parameters of a functions as raw strings, the same way this can be done when the assignment of the file and the output workspace is done through a variable in a script ie

inputfile = r"C:\tmp\Data\Data.dbf"
outputworkspace = r"D:\Data\2010_12\Output"

or any function applied to the parameters that will return them to a generic format? I have tried so far os.path.normpath() or string.encode()

for the issue with the inputfile I have found the way to get around it by the following:

Dummy = inputfile.replace('\t','\\t'); inputfile = Dummy; del Dummy   

Which I can repeat for all the escape characters or create another method that does exactly this, but the same cannot be done for the

"\2010_12"    

escape which is "read" by python as

"\x810_12"   

Since it wouldn't be the "proper" way to program

I have already read solutions such as using "/" or "\\\\", but I am wondering if there is any way to pass the input parameters of a method as raw themselves.

Adding an example:

# -*- coding: ascii -*-
import os

def printpaths(file,outputworkspace):
    print file
    print outputworkspace

printpaths('C:\tmp\Data\Data.dbf','D:\Data\2010_12\Data')

Help would be greatly appreciated
Thanx in advance

Where do you get the paths from? input from a user?

In that case, there are ways:

Python 2.7.1 (r271:86832, May  6 2011, 10:39:37) 
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> raw_input("filename: ")
filename: C:\tmp
'C:\\tmp'
>>> raw_input("output: ")
output: D:\Data\2010_12\Output
'D:\\Data\\2010_12\\Output'

Or was it something else you were after?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM