Writing text files

Updated on 28 Dec 2022

Writing to files is similar to reading from files. You will need to

  • Open file
  • Write to file
  • Close file

Basic example

Here is a basic example of writing to a file.

myString = 'This is my first line of stuff written'

with open('data/dummyWrite5.txt', 'w') as f:
    f.write(myString)

Remember that the with keyword is used in Python for compound statements. In this example, closing the file is done automatically because of the use of the with keyword.

Curious example

How about this example. What do you think might happen?

myString = 'This is my first line of stuff written'

with open('data/dummyWrite6.txt', 'w') as f:
    f.write(myString)
    f.write('what will happen now?')

Interestingly enough f.write doesn’t automatically add a newline to the file, so the 2 strings will be written to the file side by side.

I/O Strategies

The previous example has some advantages and disadvantages. The main disadvantage is that the multiple f.write statements are inefficient. This is like saying I want to copy and paste this paragraph, but I can only do 1 word at a time. Obviously for the code it would be more efficient to have a single f.write statement that could write all of our data at once. We already know how to do this with string concatenation.

If having multiple f.write statements is inefficient, what possible advantage could it offer? Consider the following code snippet.

f.write('start complex process')
# do really complex process
f.write('finish complex process')

If somewhere in our really complex process the python script crashed, we would have a file that contained ‘start complex process’ but not ‘finish complex process’. If this were a logfile then we’d have a very strong indication that something within ‘really complex process’ crashed. Consider the alternative

log_str = "start complex process\n"
# do really complex process
log_str = log_str + "finish complex process\n"

f.write(log_str)

Now what would happen if something crashed in ‘really complex process’. For a start everything afterwards would not get executed, and as a consequence we wouldn’t even have the log file!

Files - guided exercise

f.write only accepts strings, however a lot of our coding will deal with lists. What is a good way to write a list to a text file so that this list:

mylist = ['this is a line', 'another line', 'third line is a winner']

ends up in a text file looking like this?

this is a line
another line
third line is a winner

Solution

We’ve already encountered a str.split() method that split a string into a list. Perhaps there is another function that does the opposite? The list methods don’t help, but there is a string method join that will help. It says:

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

So if I read this correctly, I should be able to do this:

mylist = ['this is a line', 'another line', 'third line is a winner']
mystr = "\n".join(mylist)

with open('data/file-write-guided.txt', 'w') as f:
    f.write(mystr)