Writing Results to a File

We have seen how to read text from files (Section 3.1). It is often useful to write output to files as well. The following code opens a file output.txt for writing, and saves the program output to the file.

>>> words = set(nltk.corpus.genesis.words('english-kjv.txt'))

Your Turn: What is the effect of appending \n to each string before we write it to the file? If you're using a Windows machine, you may want to use word + "\r\n" instead. What happens if we do output_file.write(word)

When we write non-text data to a file, we must convert it to a string first. We can do this conversion using formatting strings, as we saw earlier. Let's write the total number of words to our file, before closing it.

>>> output_file.write(str(len(words)) + "\n") >>> output_file.close()


You should avoid filenames that contain space characters, such as output file.txt, or that are identical except for case distinctions, e.g., Output.txt and output.TXT.

Was this article helpful?

0 0

Post a comment