3

I've a variable "title" that I've scraped from a website page that I want to use as the file name. I've tried many combinations to no avail. What is wrong with my code?

f1 = open(r'E:\Dp\Python\Yt\' + str(title) + '.txt', 'w')

Thank you,

0

2 Answers 2

2

The syntax highlighting in the question should help you out. A \' does not terminate the string -- it is an escaped single tick '.

As this old answer shows, it is actually impossible to end a raw string with a backslash. Your best option is to use string formatting

# old-style string interpolation
open((r'E:\Dp\Python\Yt\%s.txt' % title), 'w')
# or str.format, which is VASTLY preferred in any modern Python
open(r'E:\Dp\Python\Yt\{}.txt'.format(title), 'w')
# or, in Python 3.6+, the new-hotness of f-strings
open(rf'E:\Dp\Python\Yt\{title}.txt', 'w')

Or else add even more string concatenation, which seems measurably worse.

open(r'E:\Dp\Python\Yt' + "\\" + str(title) + '.txt', 'w')
Sign up to request clarification or add additional context in comments.

Comments

0

Need to escape all them slashes boyo, otherwise they will be escaping the characters that follow.

f1 = open(r'E:\\Dp\\Python\\Yt\\' + str(title) + '.txt', 'w')

1 Comment

Nope, that's what the raw string is for (note the preceding r in front of the string's quotes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.