Get parameters as file path without baslashes

506
2
05-06-2022 10:00 AM
AntoinePrince
New Contributor

I am fairly new to python toolbox and I am trying to input a text file path into my script to further use with pandas (pd.read_csv()). However, everytime I extract my parameter, the file path returned uses '\' as separator. If I've learn one thing in Python, is that you never want to use backslashes. How do I get rid of those or how can I get my parameter to know that the string is a file path and read it appropriately.

 

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="File path to enter",
        name="path",
        datatype="DETextfile",
        parameterType="Required",
        direction="Input")

    params = [param0]

    return params

def execute(self, parameters, messages):

    path = parameters[0].valueAsText
    arcpy.AddMessage(path)

Output : 

C:\Users\xxx\FileName.txt

The pd.read_csv function does not accept this file path format.

Thanks!

 

0 Kudos
2 Replies
RhettZufelt
MVP Frequent Contributor

Haven't worked with python toolbox's here, but you could try something like:

path = "r'" + parameters[0].valueAsText + "'"

and see if the output looks like either of these:

r'C:\Users\xxx\FileName.txt'
or
'C:\\Users\\xxx\\FileName.txt'

Both of which would be valid python filepaths.

R_

Luke_Pinner
MVP Regular Contributor

@AntoinePrince wrote:

If I've learn one thing in Python, is that you never want to use backslashes.


I've been using python for a very long time and can confidently say that backslashes are fine to use.  The only issue is that new users don't realise that when you have a string literal in your code you need to escape backslashes or use raw string syntax (neither of which are applicable when you're passing a string in as a parameter).

The backslashes used in the path in your parameter will be understood just fine by pandas. I have just tested and pd.read_csv worked as expected with backslashes.

There's something else going on.  Please paste in the error message you are getting.

0 Kudos