Skip to content

Writing to files with Python

Python provides several ways to write data to a file, including using the built-in open() function and the with statement. In this article, we’ll cover how to write to a file with Python using these methods.

Using the open() Function

The open() function is the most basic way to write to a file in Python. It takes two arguments: the filename and the mode. The mode argument specifies the file mode, which can be ‘r’ for reading, ‘w’ for writing, or ‘a’ for appending.

Here’s an example of how to write to a file with Python using the open() function:

file = open('example.txt', 'w')
file.write('Hello, world!')
file.close()


In this example, we create a new file called example.txt in write mode using the open() function. We then write the string ‘Hello, world!’ to the file using the write() method of the file object. Finally, we close the file using the close() method.

Using the print() Function

The print() function in Python has an optional file argument that allows you to specify the file object to write to. Here’s an example of how to print to a file with the print() function:

Here’s an example:

with open('example.txt', 'w') as file:
    print('Hello, world!', file=file)


You can also format the output of the print() function before writing it to a file. Here’s an example of how to format the output of the print() function:

with open('example.txt', 'w') as file:
    name = 'John'
    age = 30
    print(f'{name} is {age} years old.', file=file)

Using the with Statement

The with statement is a more Pythonic way to write to a file. It automatically handles closing the file, even if an exception is raised. Here’s an example of how to write to a file with Python using the with statement:

with open('example.txt', 'w') as file:
    file.write('Hello, world!')


In this example, we use the with statement to open the example.txt file in write mode. We then use the write() method to write the string ‘Hello, world!’ to the file. The with statement automatically closes the file after the block of code is executed.

See also  Reading and Writing XML Files in Python with Pandas

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.