< previous | Table of Contents | next > |
7.5 WRITING TO FILES
By the built-in Python methods for writing into files we can edit existing content in files and add to their contents through appending to files.
WRITING STRINGS
The .write()
method writes a single line to a file. If we want the subsequent line to start from a new line, we must enter the newline \n
at the end of the string.
As w
overwrites the existing file, now the file will look like this instead.
We can use .writelines()
to write multiple items into a file, such as a list of strings. It takes a list of strings and writes them in order in the file. Note that this method does not add new line characters \n
between items. It expects that each string in the iterable ends with any necessary separators, so you must add them yourself.
The code block below overwrites the existing file and adds these lines each on an existing line to the text file using the .writelines()
method.
lines = ["First line\n", "Second line\n", "Third line\n"] file = open(file_path, 'w') file.writelines(lines)
Note, that we will cover lists in more detail in the next chapter of this course.
NB! As mentioned, opening a file in write mode will delete the existing content. So, to avoid accidentally erasing important data, it's a good idea to check if the file has important content before you open it in write mode. Or, you can use append mode a
if you want to add to the file without deleting anything.
APPENDING TO FILES
When you want to add content to the end of an existing file without erasing its current content, use the append mode. Opening a file in a
mode positions the file cursor at the end of the file, ready to add new content. Now based on the example below, the lines would be added to the end of the file and the existing file would not be overwritten.
lines = ["First line\n", "Second line\n", "Third line\n"] file = open(file_path, 'a') for line in lines: file.write(line)
KEY THINGS TO REMEMBER
write()
method is used to write a single string into a file. It requires any necessary formatting, such as newline characters\n
be included explicitly in the string.writelines()
takes a list of strings and writes them all to the file without adding any separators. The strings must manually include newlines to format the output across multiple lines.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |