The first step in writing to a file is opening it, but this time for output:
outfile = open (“out.txt”, “w”)
The “w” as the second parameter to open() means to open the file for writing. When writing to a file, it is important to note that opening it will create a new file by default. If a file with the given name already exists, it will be re-written, and the previous contents will be deleted.
The basic file output function is write(); it takes a parameter, a string to be written to the file. It only writes strings, so numbers and other types have to be converted into strings before being written. Also, there is no concept of a line. This function simply moves characters to a file, one at a time, in the order given. In order to write a line, an end of line character has to be written. This is usually specified in a string as \n, spoken as “backslash n.” The “n” stands for newline.
Example: Write a table of squares to a file.
This example illustrates the typical code involved in writing to a file. The file must be opened, then a loop from 0 to 25 is constructed. Each number in that range is written to the file, as is that number multiplied by itself. Each output string represents a line, and so must have a newline character added to the end.
outfile = open (“out.txt”, “w”)
outfile.write (” X X squared \n”)
for i in range (0, 25):
sout = ” “+str(i)+” “+str(i*i)+”\n”
outfile.write (sout)
outfile.close()
Note that the integers are explicitly converted into strings and concatenated into a line to be written. The elements of the line could be written in separate calls:
outfile = open (“out.txt”, “w”)
outfile.write (” X for i in range (0, 25):
outfile.write (” “)
outfile.write (str(i))
outfile.write (” “)
outfile.write (str(i*i))
outfile.write (“\n”)
outfile.close()
The output file is closed after all data has been written.
1. Appending Data to a File
Opening the file in “w” mode starts writing at the beginning of the file, and will result in existing data being lost. This is not always desirable. For example, what if a log file is being created? The log should contain a record of everything that has happened, not just the most recent action.
Opening the file in append mode, signified by the parameter “a,” opens the file for output and starts writing at the end of the file if it already exists. This means that data can be added to the end of an existing file.
Example: Append another 20 squares to the table of squares file.
The previous example created a file named “out.txt” and wrote 26 lines to it. It was a table of squares, and the final one was 24. This example will therefore begin at 25 and add 20 more values to the table.
The main difference is the opening of the output file in append mode, and starting the loop at 25 instead of at 0:
outfile = open (“out.txt”, “a”)
for i in range (25, 45):
sout = ” “+str(i)+” “+str(i*i)+”\n”
outfile.write (sout)
outfile.close()
The file “out.txt” will contain the squares of the integers between 0 and 44, inclusive, after this program runs.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.