In this lecture, we will explore reading and writing plain text files.
We will learn:
We can use open()
to read and write plain text file. There are 3 modes when opening a file:
r
for reading.w
for over-writing.a
for appending.👇🏻 Please note that we need to specify encoding="utf-8"
in Windows for the open
function.
with open("quotes.txt") as file_obj:
quotes = file_obj.read().splitlines()
quotes
['I want to put a ding in the universe.—Steve Jobs', 'Life is 10% what happens to you and 90% how you react to it.—Charles R. Swindoll', "Family is not an important thing. It's everything.—Michael J. Fox", "Nothing is impossible, the word itself says 'I'm possible'!—Audrey Hepburn", 'There are two ways of spreading light: to be the candle or the mirror that reflects it.—Edith Wharton', "Try to be a rainbow in someone's cloud.—Maya Angelou", 'Be brave enough to live life creatively. The creative place where no one else has ever been.—Alan Alda', 'The secret of getting ahead is getting started.—Mark Twain']
with open("quotes.txt", encoding="utf-8") as file_obj:
quotes = file_obj.read().splitlines()
quotes
['I want to put a ding in the universe.—Steve Jobs', 'Life is 10% what happens to you and 90% how you react to it.—Charles R. Swindoll', "Family is not an important thing. It's everything.—Michael J. Fox", "Nothing is impossible, the word itself says 'I'm possible'!—Audrey Hepburn", 'There are two ways of spreading light: to be the candle or the mirror that reflects it.—Edith Wharton', "Try to be a rainbow in someone's cloud.—Maya Angelou", 'Be brave enough to live life creatively. The creative place where no one else has ever been.—Alan Alda', 'The secret of getting ahead is getting started.—Mark Twain']
import random
quote = random.choice(quotes)
print(quote)
Family is not an important thing. It's everything.—Michael J. Fox
import datetime
content = input("What do you want to say to Mr. Diary? ")
if len(content) > 0:
with open('diary.txt', "a") as file_obj:
today = datetime.date.today().isoformat()
file_obj.write(today + ": " + content + "\n")
with open('diary.txt', "r") as file_obj:
lines = file_obj.readlines()
for line in lines[-3:]:
print(line.rstrip())
What do you want to say to Mr. Diary? Hello python. 2020-06-11: Hello 2020-06-11: Hello 2020-08-10: Hello python.
In this section, we learned to read and write plain text file.