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, the write method 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, use write mode (’w’). If the file 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 the write method to write a string to the file.
Rather than replacing the file contents, you can also add to a file using append mode (’a’). When you write to a file that is opened in append mode, the data you write is added to the end of the file, and the current file contents are not overwritten. For example, to add to your previous file topics.txt, you can append the words Software Engineering:
| | with open('topics.txt', 'a') as output_file: |
| | output_file.write('Software Engineering') |
At this point, if you print the contents of topics.txt, you’d see the following:
| | Computer ScienceSoftware Engineering |
Unlike the function print, the 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 ’\n’.
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 from the module typint as the type annotation for an open file. “IO” is short for “Input/Output.” Your 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 |
| | |
| | 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 = f'{number_pair} {total}\n' |
| | 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) |
File/URL reader is often opened outside the reading function
Notice that parameters are open files. That is why you 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 the following contents:
| | 1.3 3.4 4.7 |
| | 2 4.2 6.2 |
| | -1 1 0.0 |