Why does my path fail if filename contains single-quote/apostrophe?

Viewed 1975

The file here exists, 100%:

path = "~/Music/Youtube_dl/Some Artist - 'On + Off'.m4a"
assert os.path.exists(path)

But the above always fails.

If I change my actual file name to test_file.m4a and do:

path = "~/Music/Youtube_dl/test_file.m4a"
assert os.path.exists(path)

Everything works fine.

So the issue is 100% in the filename. However, I can't see to solve it. I've tried prepending a u before the string and all sorts of other solutions but none seemed to help.

Note: I'm getting filenames from an external source and can't control the fact some of them have single quotes/ quotes in them.

1 Answers

The ~ is a shell construct, python knows nothing about it. Even os.path.exists('~') fails. Assuming it is exported, we can use the environment variable HOME:

import os
import os.path
path = "~/Music/Youtube_dl/Some Artist - 'On + Off'.m4a"

path = path.replace('~', os.environ['HOME'])
assert os.path.exists(path)

Alternative you could use os.path.expanduser (which is reasonably portable):

import os.path
path = "~/Music/Youtube_dl/Some Artist - 'On + Off'.m4a"

path = os.path.expanduser(path)
assert os.path.exists(path)
Related