DEV Community

Mike Kameta
Mike Kameta

Posted on

100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 24 (File, Directories and Paths)

  • Calling a file
with open("high_score.txt", mode="a") as file:
    contents = file.read()
    print(contents)

Enter fullscreen mode Exit fullscreen mode
  • Absolute and relative paths
# Absolute path
# with open("/Users/Tumatauenga/OneDrive/Desktop/my_file.txt") as file:
#     contents = file.read()
#     print(contents)

# Relative path
with open("../../../OneDrive/Desktop/my_file.txt") as file:
    contents = file.read()
    print(contents)

Enter fullscreen mode Exit fullscreen mode
  • Mail Merge

main.py
invited_names.txt
starting_letter.txt

  • main.py
PLACEHOLDER = "[name]"

with open("./Names/invited_names.txt") as names_file:
    names = names_file.readlines()
    print(names)

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(PLACEHOLDER, stripped_name)
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name},txt", mode="w") as completed_letter:
            completed_letter.write(new_letter)

Enter fullscreen mode Exit fullscreen mode
  • invited_names.txt
    Aang
    Zuko
    Appa
    Katara
    Sokka
    Momo
    Uncle Iroh
    Toph

  • starting_letter.txt
    Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Mike

Top comments (0)