Gajendra D Ambi
Gajendra D Ambi

Reputation: 4233

"replace \ with \\ in python 3"

I am trying to create a tiny script to list all files in a directory of some extension. Here the user will input the path to the directory on windows.

import os    
import fnmatch
DIRECTORY = "D:\Movies" 
EXTN = "*.mp4"  
for dirname, dirnames, filenames in os.walk(DIRECTORY):
# print path to all filenames.
    for filename in filenames:
        if fnmatch.fnmatch(filename, EXTN):
            print(os.path.join(dirname, filename))

I tried

DIRECTORY.replace('\', '\\')
print(DIRECTORY)

and i get an error like this DIRECTORY.replace('\', '\') ^ SyntaxError: unexpected character after line continuation character I am trying to auto convert the windows directory path to python 3 readable path and i have hit a wall. :( update: following works

DIRECTORY = r"D:\Movies"

but the same doesnt if the path is like this

DIRECTORY = r"D:\"

Upvotes: 0

Views: 1074

Answers (3)

ShadowRanger
ShadowRanger

Reputation: 155418

Use raw strings in the first place, you don't need to replace (the extra slash you think you need is displayed for the repr to show the backslash was escaped, it's not actually part of the string).

For example r'D:\Movies has no risk of the backslash being misinterpreted (and if you show the repr, it will appear to have two slashes, but it makes it easier to type by using raw strings with just one).

And for anything input by the user, it's not a string literal, so backslash escapes aren't processed in the first place, they'd already be correct.

Upvotes: 3

Natecat
Natecat

Reputation: 2182

The character\ is used to escape things that have significance outside of a string. What is happening here is the backslash is escaping the first quote meaning the last quote doesn't have a quote to end on this. To fix this, escape all the backslashes by doing this: DIRECTORY.replace('\\', '\\\\')

Upvotes: 0

xiº
xiº

Reputation: 4687

You need to escape special characters:

 DIRECTORY.replace('\\', '\\\\')

Upvotes: 0

Related Questions