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,
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,
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')
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')