LESSON 02 –
FILE I/O – WRITING TO A FILE

 

 

LESSON NOTE/GUIDE

LINKS TO INFORMATION ON FILE I/O:

 

            https://www.tutorialspoint.com/python/python_files_io.htm

            https://www.javatpoint.com/python-files-io

 

PROGRAM 1 – WRITING TO A FILE

THE CODE

 

#Creates file (or overwrites file if it exists)
my_file = open("data2.txt", "w")  #w=writing
 
my_file.write("hi")
my_file.write("Go!")
my_file.write("ha\nha\nha")  #\n equals Enter

EXPLANATION

 

The above code will write the following into a file:

 

hiGo!ha
ha
ha

 

In the first line of code, we create/overwrite the file data2.txt for writing only.  If the file doesn’t exist, the file is created.  If the file already exists, it is overwritten.

 

The next three lines write strings to the file.  Note that the backslash n escape character means that the cursor needs to go to the next line.

 

 

PROGRAM 2 – APPENDING TO A FILE

 

·        This program writes to the end of the file.

THE CODE

 

#Opens file to append content to the end
my_file = open("data2.txt", "a")  #a=append
 
my_file.write("\nAdding to the end")

EXPLANATION


The first line opens the file data2.txt for appending to the end of it.  Appending simply means adding to the end of the file.

 

Note that if the specified file doesn’t exit, it is created.

 

The second line simply write the string to the end of the file.

 

 

PROGRAM 3 – WRITE 1 to 99 IN A FILE

 

  • This program writes numbers 1 to 99 one number at a time into a file.

 

THE CODE

 

my_file = open("data3.txt", "w")
for x in range(1, 100):
    my_file.write(str(x) + "\n")

EXPLANATION


The first line of code opens a file for writing.

 

The second line of code makes Python loop 100 times.  The first time, x is 1.  The next time, x is 2. And so on until x is 99.

 

The third line is inside the loop.  This lines first convers x to its string version.  It then adds a next line character to string and writes it to the file.

 

  

PROGRAM 4 – COPYING CONTENT FROM ONE FILE TO ANOTHER

 

  • This program reads the content from one file and copies it to another file.

 

THE CODE

 

def copyFile(src_filename, dest_filename):
    source = open(src_filename, "r")
    dest = open(dest_filename, "w")
    str = source.read()
    dest.write(str)
    source.close()
    dest.close()
 
 
copyFile("data.txt", "data3.txt")

EXPLANATION

 

At the very top, we create a function named copyFile that gets the filenames of the source file and destination file as parameters. 

The next 6 statements inside the function open the two files, read the data from the source, write that data to the destination and then close the two files.

 

Finally, on the last line of code, where the program execution actually begins, we call the function along with two filenames.