'Reading a file that is inside of a folder in python

Good morning

What i would like to do is reading a file called "email.txt" that is inside of a folder call "templates" and "templates" is inside of a folder called "Day_10" ,so my enviroment looks something like this:

PROYECTOS
--Day_10
------templates
----------email.txt
------file_manager.py

Note: file_manager.py in inside of Day_10 and not inside of templates, file_manager.py is where i writing my code

So, email.txt has the following message: " Hello {name}"

And i write the following code in order to read the file:

email_txt=r"templates\email.txt"
content=""

with open(email_txt, 'r') as f:
 content = f.read()

print(content.format(name="Brayan"))

But when i run the code i get the following error:

 & D:/python.exe d:/PROYECTOS/Day_10_files/file_manager.py
 File "<stdin>", line 1
 & D:/python.exe d:/PROYECTOS/Day_10_files/file_manager.py
 ^
 SyntaxError: invalid syntax

And i don't know what to do, i've been here for hours trying to get it right. i'm on windows

Hope someone can helps me.

Thanks



Solution 1:[1]

the problem is email_txt is equal to "templates\email.txt".

You have a back slash.

Try with forward slash:

email_txt="templates/email.txt"

Full Code:

email_txt="templates/email.txt"
content=""

with open(email_txt, 'r') as f:
 content = f.read()

print(content.format(name="Brayan"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sivayogeith Umamaheswaran