Writing Files

This program opens a file called topics.txt, writes the words Computer Science to the file, and then closes the file:

 with​ open(​'topics.txt'​, ​'w'​) ​as​ output_file:
  output_file.write(​'Computer Science'​)

In addition to writing characters to a file, method write returns the number of characters written. For example, output_file.write(’Computer Science’) returns 16.

To create a new file or to replace the contents of an existing file, we use write mode (’w’). If the filename doesn’t exist already, then a new file is created; otherwise the file contents are erased and replaced. Once opened for writing, you can use method write to write a string to the file.

Rather than replacing the file contents, we can also add to a file using append mode (’a’). When we write to a file that is opened in append mode, the data we write is added to the end of the file and the current file contents are not overwritten. For example, to add to our previous file topics.txt, we can append the words Software Engineering:

 with​ open(​'topics.txt'​, ​'a'​) ​as​ output_file:
  output_file.write(​'Software Engineering'​)

At this point, if we print the contents of topics.txt, we’d see the following:

 Computer ScienceSoftware Engineering

Unlike function print, method write doesn’t automatically append a newline; if you want a string to end in a newline, you have to include it manually using ’ ’.

The next example, in a file called total.py, is more complex, and it involves both reading from and writing to a file. Notice that it uses typing.TextIO as the type annotation for an open file. “IO” is short for “Input/Output.” Our input file contains two numbers per line separated by a space. The output file will contain three numbers per line: the two from the input file followed by their sum (all separated by spaces).

 from​ typing ​import​ TextIO
 from​ io ​import​ StringIO
 
 def​ sum_number_pairs(input_file: TextIO, output_file: TextIO) -> None:
 """Read the data from input_file, which contains two floats per line
  separated by a space. output_file for writing and, for each line in
  input_file, write a line to output_file that contains the two floats from
  the corresponding line of input_file plus a space and the sum of the two
  floats.
  """
 
 for​ number_pair ​in​ input_file:
  number_pair = number_pair.strip()
  operands = number_pair.split()
  total = float(operands[0]) + float(operands[1])
  new_line = ​'{0} {1}​​ ​​'​.format(number_pair, total)
  output_file.write(new_line)
 
 if​ __name__ == ​'__main__'​:
 with​ open(​'number_pairs.txt'​, ​'r'​) ​as​ input_file,
  open(​'number_pair_sums.txt'​, ​'w'​) ​as​ output_file:
  sum_number_pairs(input_file, output_file)

Notice that parameters are open files. That is why we don’t need to call function open inside the function. Instead, that happens in the main program.

Assume that a file called number_pairs.txt exists with these contents:

 1.3 3.4
 2 4.2
 -1 1

Then this program creates a file named number_pair_sums.txt with these contents:

 1.3 3.4 4.7
 2 4.2 6.2
 -1 1 0.0
..................Content has been hidden....................

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