In Dictionary operations, we learned how to maintain a database of countries and
capitals.
But did you notice, that once you close the program all the
entries you made are lost?
Next time you run it, you will have to re-anteater all the things
again..isn’t it?
Won’t it be good if you can store it and use it later?
What if, we could write all the Dictionary details into a text file so that you can refer to them later on.
Today we will see how we can read/write into a text file (extension
.txt).
Opening a file :
open(<filename>,<access_mode>)
<filename> refers to the name of the file(with extension) to be
opened.
<access_mode> determines the type of operation that is permitted.
Note The file should be present in the same location as the .py
file, else the complete path of the file needs to be given.
Note: Each line in the text file has a newline character (‘\n’) at the
end. You may use strip() to remove this. strip() removes the character at the beginning or end of a
string.
Syntax to access a file
with open(<filename>,<access_mode>) as < file_object > :
Note: When a file is opened in this method, it automatically closes
the file after use.
Write the quote “Why fit in when you are born to stand out?” to a file
named quotes.txt.
Note: ‘file=’ in print. ’file’ determines where to
print the message. Earlier we were using print without it because by
default it prints to screen.
Open the file quotes.txt and see.
Write another quote “No act of kindness, no matter how small, is
wasted” to the same file.
Note: Open file “quotes.txt” and see how it replaced the
earlier quote.
Write the quote “Why fit in when you are born to stand out?” to the
same file in append mode.
Note: Open file “quotes.txt” to student and show how the quote got
appended to the existing file.
Read the file quotes.txt using readlines and print the quotes one by
one.
Note: Show ‘\n’ at end of each quote in the list
Note: here strip() removes the newline(‘\n’)
Create a to-do list manually. quote filename to be used is
“mytodolist.txt”. Create the file at the same location as to-our program.
Write a program to display the items in the todo list one by one.
Write a program to append items to the to-do list.
Write a program to display the entire thing as a list.
Note: All the operations on lists can be performed on this list created
above.
Comments
Post a Comment