TIL: Python Basics Day 24 - Local Files and Directories/ Mail Merge Challenge

이다연·2021년 1월 5일
0

Udemy Python Course

목록 보기
24/64
post-thumbnail

Working with Local Files and Directories

Files

Open & Close the file

-we always need to mannually close the file. It will need to free up the space at some point, and as it takes up resources on your computer; however, by using 'with', we don't need to write close.

file = open("name_of_file")
file.close()

<simplified ver>
->
with open(“file.txt”) as file: #(saved it into a variable called 'file')
    contents = file.read()
    print(contents)

Write on the file.txt

  • mode=w : override the existing texts or if you don't have an existing file, it will create a new file
  • mode=a : append the texts on an existing file.
with open("file.txt", mode="w or a") as file: 
    file.wrtie("\nNew Text.")

Task1. record the highest score on snake game

I created a data.txt file and wrote 0.
On scoreboard.py, for init attribute high_score' value, read from data.txt.
on reset(), write self.highscore on a data.txt file after comparing current score to highest score.

Paths

Root: /

 mac: Machintosh HD (hard drive) 
 windows: C: -> root folder  

1. Absolute File Path:

starts from the origin (root), alwalys relative to the root
e.g. /Work/Project/work.doc

2. Relative File Path:

we are currently working from, relative to your current Working Directories.
Depending on where you are and where you are trying to get to.

-> adapt to the situation and figure out which one is the most appropriate.

How to write relative paths

1. when going down the hierarchy

"./talk.ppt" (when we know that we are already at Project folder)

2. when going up the hierarchy
two dots represents going up step up to the parent folder.

"../report.doc" (we are at a folder below the file)

3. when within the same directory, get access to another file

"./report.doc" 

or 

"report.doc" (get rid of dot and slash)

"../../Desktop/my_file.txt"

UP: except for the current folder, see how many steps to reach the same parent folder. -> state it as ..
DOWN: write all the parents folders

Taks 2. Mail Merge Challenge

1. The replace() method replaces a specified phrase with another specified phrase.

txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x) 

2. readlines(): Return all lines in the file, as a list where each line is an item in the list object:

f = open("demofile.txt", "r")
print(f.readlines()) 

3. String strip() Method

Remove spaces at the beginning and at the end of the string:
It keeps the space in between the words

txt = "     banana     "
x = txt.strip()
print("of all fruits", x, "is my favorite") 

main.py

main.py was on a same hierarchical level as Input, Output folder.

#TODO: Create a letter using starting_letter.docx 
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
    
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
    #Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
        #Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp


#TODO 1: create list of names: how can I count number of words in a txt file? / is that already a list?
def names():
    open_names = open("Input/Names/invited_names.txt", "r")
    names= open_names.readlines()
    return names

#TODO 2: fetch the names on main.py as a list/ & strip \n
name_list = names()

names = []
for name in name_list:
    letter = name
    word = letter.strip()
    names.append(word)

#TODO 3: create txt files using with, it's an empty txt file -> fetched content from starting_letter
with open("Input/Letters/starting_letter.txt") as data:
    content = data.read()
#TODO 4: ?? replace [name] from the names list (is it okay to use txt file instead of docx?)
#TODO 5: save each letters onto ReadyToSend folder.
#TODO 6: loop through from create to save
for name in names:
    with open(f"Output/ReadyToSend/Letter to {name}.txt", mode="w") as file:
        result = content.replace("[name],", f"{name},")
        file.write(result)

Optimize for readability! (at this stage and later on syntax, style, ideas)

open_names = open("Input/Names/invited_names.txt", "r")
names_list= open_names.readlines()

stripped_names= []
for name in names_list:
    word = name.strip()
    stripped_names.append(word)

with open("Input/Letters/starting_letter.txt") as data:
    content = data.read()

for name in stripped_names:
    with open(f"Output/ReadyToSend/Letter to {name}.txt", mode="w") as file:
        name_replaced_letter = content.replace("[name]", f"{name}")
        file.write(name_replaced_letter)

Angela's solution

PLACEHOLDER = "[name]"


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

with open("./Input/Letters/starting_letter.docx") 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}.docx", mode="w") as completed_letter:
            completed_letter.write(new_letter)
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글