Writing Files
To write something to a file, you can do this:
with open('example.txt', 'w') as file:
file.write('hello\n')
file.write('world\n')
You can use the same with...as
statement as when reading a file, except you
need to add 'w'
as a second parameter to indicate that you want to write to
the file. The file will be automatically closed once you finish writing.
Be careful when writing files! If the file you open for writing does not exist, Python will create a new, empty file. But if the file you open for writing already exists, Python will erase everything and make it a new, blank file.
Copying a file
This example demonstrates how to read from one file and write to another file at the same time:
with open('boring_file.txt') as infile:
with open('exciting_file.txt', 'w') as outfile:
for line in infile:
outfile.write('⭐️ ')
outfile.write(line)
If the file called boring_file.txt
contains:
Once there was a cat
who slept all day
Then after this code runs, the file exciting_file.txt
will contain:
⭐️ Once there was a cat
⭐️ who slept all day
Notice that in this code we have two with ... as
statements that are nested.
Each time we use with ... as
we need to indent code inside the block. All code
inside this doubly-indented block has access to infile
for reading and
outfile
for writing.
With both files open (one for reading, one for writing), we can now read lines
from infile
and write lines to outfile
.
Writing numbers to a file
If you try to write a number to a file:
with open('numbers.txt', 'w') as file:
file.write(42)
This will not work! You can only write strings. Remember, you can convert a
number to a string with str()
:
with open('numbers.txt', 'w') as file:
file.write(str(42))
Writing a list of numbers to a file
If you want to write a list of numbers to a file, convert them to strings first, and then use this helpful function:
def list_of_numbers_to_string(list_of_numbers):
return " ".join(list_of_numbers)
This function uses join
, something we explain in the next unit.
For example, when we run this code:
def list_of_numbers_to_string(list_of_numbers):
return " ".join(list_of_numbers)
numbers = ['1', '2', '3']
result = list_of_numbers_to_string(numbers)
then result
will store the value 1 2 3
.
A bigger example
Here is an example of how to use this function. We want to read a file of numbers and add 2 to each number. An input file may have this in it:
1 2 3
10 11 12
We want the output file to have this:
3 4 5
12 13 14
Here is a program that will do this:
def list_of_numbers_to_string(list_of_numbers):
''' Convert a list of numbers (where each number is a string) to a single
string, where the numbers are separated by spaces.'''
return " ".join(list_of_numbers)
def get_lines(filename):
''' get all the lines of a file and return the lines in a list'''
with open(filename) as file:
return list(file)
def add_two_to_each(line):
''' Go through all of the numbers in a line, convert them to a integer,
add 2, and then convert back to a string. Return all of the numbers as
a list of strings'''
numbers = []
words = line.split()
for word in words:
numbers.append(str(int(word) + 2))
return numbers
def add_two(input_file, output_file):
''' add 2 to every number in an input file, and write the new numbers
to an output file'''
lines = get_lines(input_file)
with open(output_file, 'w') as outfile:
for line in lines:
numbers = add_two_to_each(line)
string = list_of_numbers_to_string(numbers)
outfile.write(string + '\n')
add_two('input.txt', 'output.txt')
This is the logic of add_two()
:
- get all of the lines from the input file
- for each line
- convert each line to a list of numbers, where each number is the same as in the original line, plus two
- convert the list of numbers to a string
- write the string to the output file
The add_two_to_each()
function takes a line that is a string: '1 2 3'
and
converts it to a list of numbers: ['3', '4', '5']
. Notice that each number is
still a string, and we have added 2 to each number. We need to keep each number
as a string so that we can give it to the list_of_numbers_to_string()
function. This function takes ['3', '4', '5']
and turns it into '3 4 5'
.