다른 명령
- a.py에 있는 변수 aa 를 b.txt 파일을 읽어서 aa 변수를 처리 하는방법
변수처리 안되는 예제
1. a.py
aa = "This" with open("b.txt", "r") as f: content = f.read() print(content)
2. b.txt
{aa} is a.py
- 실행 결과
{aa} is a.py
→ 문자열 그대로 출력될 뿐 aa가 치환되지 않습니다.
변수처리 방법
- 치환하려면 .format() 또는 f-string 사용 필요
방법 1: str.format() 사용
aa = "This" with open("b.txt", "r") as f: content = f.read() print(content.format(aa=aa))
→ 결과:
This is a.py
방법 2: f-string처럼 사용하고 싶다면 eval(f"") (주의 요망)
aa = "This" with open("b.txt", "r") as f: template = f.read() print(eval(f"f'{template}'")) # 보안상 외부 입력일 경우 비추
요약 정리
방법 | 변수 적용됨? | 설명 |
---|---|---|
f.read() 만 사용 |
X | 문자열 그대로 읽음 |
.format() 사용 |
O | 안전하고 권장 |
eval(f"f") |
O | f-string처럼 사용 가능하나 보안 주의 |
jinja2 템플릿 방식
from jinja2 import Template # 변수들 context = { "name": "Bob", "age": 25, "place": "PythonLand" } # 템플릿 읽기 with open("template.txt", "r") as f: template_str = f.read() # Jinja2 템플릿으로 처리 template = Template(template_str) result = template.render(context) print(result)