Reading and writing files
- 라임 샹큼
- Mar 24
- 2 min read
I learned how to read write txt files. I learned how to navigate files. I always wondered how people sent automated emails to so many people with just the name differing and I got to learn the fundamentals of how it worked.
PLACEHOLDER = '[name]'
with open('Input/Names/invited_names.txt', 'r') as name:
name_list = name.readlines()
print(name_list)
with open('Input/Letters/starting_letter.txt','r') as letter:
letter_content = letter.read()
for name in name_list:
stripped_name = name.strip()
new_letter = letter_content.replace(PLACEHOLDER,stripped_name)
with open(f'Output/ReadyToSend/letter_for_{name}.docx','w') as finished_ltter:
finished_ltter.write(new_letter)
The code is noticably shorter than other codes and that just reinforces the many possibilities that are possible apart from this code. It was fun learning about other file names other than .py.
Things I learned
When recording high score with python, it resets the score everytime it replays. To stop this from happening, I have to record my results into another file.
can do this by making a new file that ends with txt.
file = open('my_file.txt')contents = file.read()print(contents)file.close() #close to ensure space can call like thisthe following are the same:
file = open('my_file.txt')contents = file.read()print(contents)file.close() with open('my_file.txt') as file: contents = file.read() print(contents)with the top, need to remember to close the file but second will close after performing.
To edit the file, need to change it to writable mode.
with open('my_file.txt',mode = 'w') as file: #w means write, r means read, read by default file.write('New text.')this will replace all text that was there before with 'new text.'
can append text to the very bottom:
with open('my_file.txt',mode = 'a') as file: file.write('New text.')a means append. if you write as above, the 'new text' will completely stick to the words before it. so make sure to add \n to make it have another line before it.
absolute file paths: navigating files
/
/Work #Work file that is in root folder
relative file path- not working from the root folder but another folder
to get to Work file, just type in './talk.ppt'
Comments