Search code examples
pythonfilepathstring-literalsrawstring

Alternative way to change from a string literal to a raw string literal when reading in a file path


I am writing a function and my input parameter is the file path: C:\Users\HP\Desktop\IBM\New folder

def read_folder(pth):
    for fle in Path(pth).iterdir():
        file_name = Path(pth) / fle
    return file_name

For me to use this function, I need to specify r'' in the file path, ie.

read_folder(r'C:\Users\HP\Desktop\IBM\New folder')

Is there a way where I can avoid specifying r'' in the file path, ie. like the below and the code would work.

read_folder('C:\Users\HP\Desktop\IBM\New folder')

The reason why I want to do this is so to make it easier for the user to just copy and paste the directory path into the function and just run the function. So it's more for ease-of-use on the user end.

Many thanks.


Solution

  • You can't really do that because without prepending r to your string there's no way python interpreter would know that your string contains \ intentionally and not on purpose to escape the characters.

    So you've to either use r"C:\Users\HP\Desktop\IBM\New folder" or "C:\\Users\\HP\\Desktop\\IBM\New folder" as argument while calling read_folder function.