In our Previous chapter you learned how to read the file with help of Python. Now its time for Reading Writing Files with python. But before that I want you to remember and understand below functions, you have already used read function in last chapter.

  • close — Closes the file. Like File->Save.. in your editor.
  • read — Reads the contents of the file. You can assign the result to a variable.
  • readline — Reads just one line of a text file.
  • truncate — Empties the file. Watch out if you care about the file.
  • write('stuff') — Writes “stuff” to the file.

For now these are the important commands you need to know. Some of them take parameters, but we do not really care about that. You only need to remember that write takes a parameter of a string you want to write to the file.

Let’s use some of this to make a simple little text editor, we will use our same old file we used in last chapter, that file have same contain as in last chapter.

from sys import argv

script, filename = argv

print ("""Here is what we will do, We will print file %s
And then erase the entire file
Add 3 line in it
\n\n\nNow I am starting to erase that file
if you want me to stop you can press ^C or else
press enter to move to next""" % (filename))

input(" ")

print ("Opening the file...")
target = open(filename, 'w')

print ("Truncating the file. Goodbye!")
target.truncate() # This will clear all data

print ("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print ("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print ("And finally, we close it.")
target.close()

That’s a large file, probably the largest you have typed in so far. So go slow, do your checks, and make it run. One trick is to get bits of it running at a time. Get lines 1-8 running, then five more, then a few more, until it’s all done and running.

What You Should See

There are actually two things you will see. First the output of your new script:

reading and writing files with python

 

Now, open up the file you made (in my case sample.txt) in your editor and check it out.

What was in code ?

Lets understand code step by step:
  • I believe you don’t need explanation till line 10.
  •  In Line 11 we have opened the file and assigned it to variable target. “w”  provides variable target write permission to file. By default you only have read permission and now you have write permission with “w”. When you use “w” python will erase current file and add new data, if you want to keen old data also you need to use “a” (append).
  • In line 13 we have used truncate function, as explained above this function will empty your file, Remember you need to have write permission to empty file.
  • Line 14 to 18 are understandable
  • Line 19 have write function, you can pass any value you want to write in your file with this function either using variable or string (line 20).
  • Write function doesn’t write in new line, instead it add the string next to old one so you will need \n to add a new line in your file. So its more like python printing in a file instead of your screen.
  • After all is done we close the file.

Easy enough.. Try it your self and you will understand.

Exercise of the Day:

Create a code to read from file 1 and write it in file 2.

 

no comments

Leave me comment