Test/Python(20220101~)

Days24. 메일 머지(mail merge)

kiostory 2022. 3. 7. 22:22

*starting_letter.txt

Dear [name],
You are invited to my birthday this Saturday.
Hope you can make it!
- kio -

 

*invited_names.txt

Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

 

[name] 위치에 invited_names 각 이름으로 대체,

 

*main.py

with open("./Input/Letters/starting_letter.txt") as letter_file:
    letter_contents = letter_file.read()
    for name in open("./Input/Names/invited_names.txt"):
        stripped_name = name.strip()
        new_letter = letter_contents.replace("[name]", stripped_name)
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", mode="w") as completed_letter:
            completed_letter.write(new_letter)

for name in open("./Input/Names/invited_names.txt"): 부분이 일반적으로 가장 먼저 생각나는 방향이겠으나,

해답은 이런 설명을 하고 있다.

 

*main.py

with open("./Input/Names/invited_names.txt") as names_file:
    names = names_file.readlines()    #dictionary로 저장해둔다
with open("./Input/Letters/starting_letter.txt") as letter_file:
    letter_contents = letter_file.read()
    for name in names:
        stripped_name = name.strip()
        new_letter = letter_contents.replace("[name]", stripped_name)
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", mode="w") as completed_letter:
            completed_letter.write(new_letter)

현실적인가...