문제


To cut a long story short. I have this function:

def save_screenshot(self, file_destination, picture_format = None)
    file_path_name, file_extension = os.path.splitext(file_destination)
    file_path, file_name = os.path.split(file_path_name)
    (...)

Now, I call the function like this:

save_screenshot("C:\Temp\picture.jpg", "JPG")

I know howto NOT escape a string in python (with the help of "os.path.join"), but I don't know howto do this, if the string is a function parameter. The function works fine (on a windows), if I write "C:\\Temp\\picture.jpg" or "C:/Temp/picture.jpg".

Would be great, if you have some advice.
thanks

도움이 되었습니까?

해결책

As mentioned you could use:

Raw String r" string "

save_screenshot(r"C:\Temp\picture.jpg", "JPG")

It should also be possible to use """ string """

save_screenshot("""C:\Temp\picture.jpg""", "JPG")

Maybe I could also reference to this answer on Stack: what-exactly-do-u-and-rstring-flags..

This basically explains how to use raw string literals in order to ignore escape sequences that derive from backslashes in Strings (mostly for regexp).

다른 팁

I thing your problem is not using os.path rather then escape/unescape string.
Would this function better?

def save_screenshot(self, file_destination, picture_format = None):
    file_name = os.path.basename(file_destination)
    path = os.path.dirname(file_destination)
    base, ext = os.path.splitext(file_name)
    e = ext if picture_format is None else '.%s' % picture_format.lower()
    to_path = os.path.join(path, base + e)
    print(to_path)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top