Issue
I have some simple code [CentOS 7 & python 3.6, because... stuck with a VM image]:
with open(filename, "r") as read_file:
# do stuff
Which is grand & wonderful - does the self-closing thing, and has no problems with spaces in filenames.
Except it can't cope with filenames with apostrophes:
Error reading Why Doesn't this Code Work?!.py: near "t": syntax error
I tried a sneaky
with open(f"{filename}", "r") as read_file:
# do stuff
And that made no difference, and even a desperate
with open(f'"{filename}"', "r") as read_file:
# do stuff
Which is just totally broken (whichever way you do the quotes)
Is there a way to do this.... noting I'm realistically stuck with python 3.6
Solution
You can solve the error by escaping the apostrophe with a back slash. Modified code:
filename = filename.replace("'","\'")
with open(filename, "r") as read_file:
# do stuff
Answered By - Dinux
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.