Skip to content

Writing Data to a File in Python Using the write() Method

Updated: at 04:34 AM

Being able to write data to a file is a crucial skill for any Python developer. Whether you need to store program data, log user activity, or interface with other systems, writing data to files in a reliable and efficient manner is a must-have ability.

In this comprehensive guide, you will learn how to write to files in Python using the built-in write() method. We will cover the fundamentals of file handling, demonstrate how to open files in different modes, write various data types to a file, manage file pointers, and use best practices for error handling and closing files.

Practical code examples are provided throughout to illustrate the concepts clearly. By the end of this guide, you will have the knowledge needed to confidently read and write files in Python for real-world programming tasks. Let’s get started!

Overview of File Handling in Python

Before diving into the specifics of the write() method, it’s important to understand some core concepts about file handling in Python:

Now that we have a high-level overview, let’s look at opening files and write modes in more detail.

Opening Files for Writing

To write to a file, you need to open it in a mode that allows writing. This is done by passing the mode as the second argument to the open() function:

file = open('data.txt', 'w')

The common file open modes are:

For example, to open a file called 'data.txt' for writing, you would use 'w' mode:

file = open('data.txt', 'w')

This will create a new blank 'data.txt' file if it doesn’t exist or clear any existing contents. Now let’s look at how to write to the opened file.

Writing Data to a File with write()

The write() method is used to write data to an open file. It accepts a string of text or bytes data, which gets written to the end of the file based on the file’s current position:

file.write('This text will be written to the file')

Some key properties of the write() method are:

Let’s see some examples of writing different data types to a file:

# Open in write mode
file = open('data.txt', 'w')

# Write string
num_written = file.write('This is some text')

# Write bytes
bytes_written = file.write(b'This is some bytes')

# Write bytearray
ba_written = file.write(bytearray(b'ByteArray'))

file.close()

Note that the write() method returns the number of bytes written which you can use to ensure the write completed correctly.

Also, note that we call file.close() when done writing to close the file and release resources.

Managing File Position Using seek() and tell()

By default, the write() method appends data to the end of the file. So how can you write data to arbitrary positions in the file?

This is done by controlling the file’s current position using the seek() and tell() methods:

For example:

# Open file and write first line
file = open('data.txt', 'w')
file.write('First line\n')

print(file.tell()) # Returns 10

file.seek(0) # Move to start of file

print(file.tell()) # Prints 0

file.write('Inserted line\n') # Inserts at start

file.close()

Using seek() and tell() gives you full control over where you write data in a file.

Writing Other Data Types

The write() method converts its input to a bytes representation to write to the file. But what about more complex Python datatypes? Here are some tips:

Strings

Numbers

Lists, Dicts

Binary Data

Here are some examples:

import json

# Numbers
file.write(str(100)) # string representation

json.dump(123.456, file) # serialized

# Lists
cities = ['Paris', 'London']
json.dump(cities, file)

# Dicts
person = {'name': 'John', 'age': 20}
json.dump(person, file)

# CSV
import csv
with open('data.csv', 'w') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['id', 'name'])
  writer.writerow([1, 'John'])

This covers the main methods for writing Python datatypes like strings, numbers, lists, and dicts to a file.

Error Handling and Best Practices

When writing files, there are some common errors and best practices worth highlighting:

Always close files - Use a try-finally block to ensure the file is closed even if an error occurs:

file = open('data.txt', 'w')
try:
   file.write('Hello')
finally:
   file.close()

Handle I/O errors - Use try-except blocks to handle errors gracefully:

try:
  file = open('data.txt', 'x')
  file.write('Test')
except FileNotFoundError:
  print('Cannot open file')
except IOError:
  print('Error writing to file')

Use context managers - Leverage the with statement to automatically close files:

with open('data.txt', 'w') as file:
  file.write('Hello') #file closed automatically

Set encoding - Set the encoding for non-ASCII characters explicitly:

with open('data.txt', 'w', encoding='utf-8') as file:
  file.write('café')

By following these best practices in your code, you can robustly handle errors and ensure proper writing of data to files.

Putting It All Together

Let’s see an example program that writes data to a file in Python:

import json

def write_data(filename):
  """Write sample JSON data to a file"""
  with open(filename, 'w', encoding='utf-8') as file:

    # Dict
    user = {'name': 'John', 'age': 20}
    json.dump(user, file)

    # List
    cities = ['Paris', 'London', 'Tokyo']
    json.dump(cities, file)

    # String
    file.write('\nThis is some text')

    # Bytes
    file.write(b'\xff\xfe')

if __name__ == '__main__':

  output_file = 'output.txt'
  write_data(output_file)

  print(f'Data written to {output_file}')

This implements some of the best practices we covered like using a context manager for opening/closing the file, handling different data types like dicts, lists, and strings, and setting the file encoding.

The result is a JSON-formatted output file with structured data written neatly and robustly. The same principles can be applied to write any kind of file-based output from your Python programs.

Conclusion

This guide covered the foundations of writing data to files in Python using the built-in write() method. Here are some key takeaways:

The techniques discussed provide the skills you need to handle most file output tasks in Python. You can now write your program’s data to files with confidence.

Whether you need to generate reports, log user activity, store serialized objects, or interface with other systems, file writing using Python’s built-in functionality is up to the task. Put these skills into practice on your next Python project that requires robust file handling.