Python: How to Escape Slashes in Path

python: how to escape slashes in path?

This is not a Python issue, but an OS issue. Your OS will not support folder names containing slash characters.

Correctly escaping backslash in python

This might be useful for your problem, concatenation is safe and you can check whether the specific file exists.

import os

filename = 'filename'
ext = '.txt'
folder = 'folder

var = os.path.join(folder, filename + ext)
exists = os.path.isfile(var)

How do I escape forward slashes in python, so that open() sees my file as a filename to write, instead of a filepath to read?

you cannot have / in the file basename on unix or windows, you could replace / with .:

page.replace("/",".") + ".txt"

Python presumes /site etc.. is a directory.

Struggling with backslashes in subprocess.run

This works:

import subprocess

subprocess.run('dir "C:/"', shell=True)

It seems windows does not like it (even in CMD) when you surround the path with single quotes. It does like it when you give it double-quotes. So use single quotes to signify string and double-quotes to surround the actual path. Furthermore, python (and Windows) don't mind if you use forward-slashes instead of backward-slashes in paths.
And yes, in this case you do need shell=True. Just try to stay away from it when you can!



Related Topics



Leave a reply



Submit