Reputation: 421
I know, it's probably a super easy problem with tons of answers here. I tried to read around but I can't find a solution to this.
I know that the backslash \
is a special character and that to escape it, I need to double it like \\
.
I want to create a string with a file name pointing to a different folder, something like fld\filename.mat
. But this string is a concatenation of the filename
given by a var_filename
with the folder name and the file extension as strings. I then use this variable to load a file into python.
I tried var = 'fld\\' + var_filename + '.mat'
but then, when I try to use it to load the file, it tells me it cannot find
fld\\filename.mat
.
While of course if I try var = 'fld\' + var_filename + '.mat'
, it gives me an end-of-line error EOL while scanning string literal
because I believe \'
it's seen as the escape for the '
.
Thanks for your help
Upvotes: 0
Views: 1450
Reputation: 381
Since you have multiple variables with different parts of the path, you can concatenate them all into one.
parent_folder = "parent_folder"
folder = "folder"
name = "file"
ext = ".py"
path = parent_folder + "\\" + folder + "\\" + name + ext
print(path)
Upvotes: 0
Reputation: 1366
This might be useful for your problem, concatenation is safe and you can check whether the specific file exists.
import os
filename = 'filename'
ext = '.txt'
folder = 'folder
var = os.path.join(folder, filename + ext)
exists = os.path.isfile(var)
Upvotes: 2