gazzar
gazzar

Reputation: 91

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?

import pathlib
from shlex import quote

path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
    f.write(content)

I'm getting this traceback

(tools) $ python test_filemake.py 
Traceback (most recent call last):
  File "test_filemake.py", line 13, in <module>
    with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"

I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

Upvotes: 0

Views: 239

Answers (0)

Related Questions