Day 24-File & Mail Merge Project


Posted by pei_______ on 2022-05-04

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


Open a file, and Close it

# Method 1
file = open("my_file.txt")
content = file.read()
print(content)
file.close()

# Method 2 
with open("my_file.txt") as file:
    content = file.read()
    print(content)

REwrite or Append the content in the file

# REwrite whole file
with open("my_file.txt", mode='w') as file:
    content = file.write("new text inside")

# Append the content after the original
with open("my_file.txt", mode='a') as file:
    content = file.write("new text inside")

If the file didn't exist, it'll make it

# make new file
with open("new_file.txt", mode='w') as file:
    content2 = file.write("new text inside")

Absolute fold path & Relative fold path

# Relative fold path
with open("../../text_on_same_disk.txt") as file:
    content = file.read()
    print(content)

# Absolute fold path
with open("/Users/Penny/Desktop/text_on_desktop.txt") as file:
    content = file.read()
    print(content)

Mail Merge Project

# Mail Merge Project


PLACEHOLDER = "[name]"

with open("Input/Names/invited_names.txt") as name_file:
    names = name_file.read().splitlines()

with open("Input/Letters/starting_letter.txt") as letter_file:
    letter = letter_file.read()

for name in names:
    with open(f"Output/ReadyToSend/letter_for_{name}.txt", mode='w') as new_file:
        new_content = new_file.write(letter.replace(PLACEHOLDER, name))

#Python #課堂筆記 #100 Days of Code







Related Posts

把問題條列化 - 自主練習

把問題條列化 - 自主練習

Event Capture, Propagation, Bubbling and Once

Event Capture, Propagation, Bubbling and Once

CSS定位 inset

CSS定位 inset


Comments