Reading and Writing to files in python is rather useful when you want to store down some of the results you get after running a program. So here is a simple stright forward guide to doing just that.
Go ahead and open up a file as ex1.py or whatever you prefer really.
$ touch ex1.py
Also create a .txt file for our dummy text file that we'll read with python.$ echo "This is a text file" >> dummytext.txt
If doing that confuses you than you can just use a text editor and create the .txt file that way same thing but the above is just a command to send the string into a file in this case dummytext.txt. cat dummytext.txt
Alright we aren't crazy and text is there. If it's not there than go ahead and do it manually and use a text editor to type it into the file or whatever method you prefer.#!/usr/bin/env python
import sys, os
def main():
f = open('dummytext.txt', 'r')
text = f.read()
print(text)
f.close()
if __name__=="__main__":
main()
Run that and you'll see the text appears that appears in dummytext.txt file. So let me explain what exactly happened.#!/usr/bin/env python
import sys, os
def main():
f = open('dummytext.txt', 'w')
f.write("New text in the file")
f.write("\n")
f.close()
if __name__=="__main__":
main()
After running that check the dummytext.txt file and you'll realize that the file has be changed to contain "New text in the file". This is because of the write() function that is avaliable for you to use when you open a file with 'w'. Also keep in mind to always close the file after opening it as this could lead to problems in more complex programs.#!/usr/bin/env python
import sys, os
def main():
f = open('dummytext.txt', 'a')
f.write("The previous text will be preserved this time.")
f.write("\n")
f.close()
if __name__=="__main__":
main()
Now when you check the file you'll see the the previous text in the dummytext is still there and the new text that was writen into the file is also there. When opening a file with 'a' you are preserving the original text in the file but appending new strings into it thus 'a' stands for appending.