Adding data to existing files

We test three ways of writing data to existing files in order to discover some basic rules of data storage.

# file_append_1.py
#>>>>>>>>>>>>>>>>>
# Open an existing file and add (append) data to it.
filename_1 = "/constr/test_write_1.dat"
filly = open(filename_1,"a") # Open a file in append mode
filly.write("
")
filly.write("This is number four and he has reached the door")
for i in range(0,5):
filename_2 = "/constr/test_write_2.dat"
filly = open(filename_2,"a") # Create a file in append mode
filly.write("This is number five and the cat is still alive")
filename_3 = "/constr/test_write_2.dat"
filly = open(filename_3,"w") # Open an existing file in # write mode
# The command below WILL fail "w" is really "overwrite"
filly.write("This is number six and they cannot find the fix")

How it works...

What make up the first method are two things: firstly, we open the file for appending ("a") which means we will add data to what is already in the file. Nothing will be destroyed or overwritten. Secondly, we separate the new data from the old with the line

filly.write(" ")

The second method works, but is a very bad practice because there is no way of separating different entries.

The third method wipes out whatever was previously stored in the file.

So remember the difference between write and append

If we keep the above three methods clear in our heads, we will be able to successfully store and retrieve our data without mishap and frustration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.38