简体   繁体   中英

python: how to escape slashes in path?

temp_dir = 'spam'
dir_name = 'foo/bar/baz.xyz'  # should be escaped somehow
dir = os.path.join(temp_dir, dir_name)
os.mkdir(dir)

I need to create directory inside temp_dir with name dir_name . But current code will produce 3 nested dirs inside temp_dir .

I've tried to replace each slash in dir_name with \\/ but os.mkdir ignores escaping with \\ and treat it as part of nested dir name.

You can't do this. In another way what would be a difference for OS between 'foo/bar/baz.xyz' as a file and 'foo/bar/baz.xyz' as a folder? I think it is a bad idea and you won't find a solution.

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

If the directory name contains a slash the OS module sees this as a : . Therefore you can create dirs containing slashes by specifying the dirname as followed os.mkdir(path + "dir:name") . The folder will be named dir/name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM