Writing Files Using Python

Basics of Writing Files in Python The common methods to operate with files are open() to open a file,


Writing Files Using Python

Basics of Writing Files in Python The common methods to operate with files are open() to open a file,

seek() to set the file’s current position at the given offset, and

close() to close th

As pointed out in a previous article that deals with reading data from files, file handling belongs to the essential knowledge of every professional Python programmer. This feature is a core part of the Python language, and no extra module needs to be loaded to do it properly.

Basics of Writing Files in Python

The common methods to operate with files are open() to open a file, seek() to set the file's current position at the given offset, and close() to close the file afterwards. The open() method returns a file handle that represents a file object to be used to access the file for reading, writing, or appending.

Writing to a file requires a few decisions — the name of the file in which to store data and the access mode of the file. Available are two modes, writing to a new file (and overwriting any existing data) and appending data at the end of a file that already exists. The according abbreviations are “w”, and “a”, and have to be specified before opening a file.

In this article we will explain how to write data to a file line by line, as a list of lines, and appending data at the end of a file.

Writing a Single Line to a File

This first example is pretty similar to writing to files with the popular programming languages C and C++, as you’ll see in Listing 1. The process is pretty straightforward. First, we open the file using the open() method for writing, write a single line of text to the file using the write() method, and then close the file using the close() method. Keep in mind that due to the way we opened the "helloworld.txt" file it will either be created if it does not exist yet, or it will be completely overwritten.

filehandle = open('helloworld.txt', 'w')
filehandle.write('Hello, world!\\n')
filehandle.close()

Listing 1

This entire process can be shortened using the with statement. Listing 2 shows how to write that. As already said before keep in mind that by opening the "helloworld.txt" file this way will either create if it does not exist yet or completely overwritten, otherwise.

with open('helloworld.txt', 'w') as filehandle:
    filehandle.write('Hello, world!\\n')

Listing 2

Writing a List of Lines to a File