Write Data to a File in Python

In Python, you can write data to a file using the open() function in write mode ("w") or append mode ("a"). The write() and writelines() methods allow you to write text or multiple lines efficiently. Let’s explore different ways to write data to a file.


Examples

1. Writing a Single Line to a File

The simplest way to write data to a file is by using the write() method.

In this example, we will use write() method to write a string (containing a single line) to a file example.txt.

main.py

</>
Copy
# Opening a file in write mode
file = open("example.txt", "w")

# Writing a single line to the file
file.write("Hello, this is a sample text.")

# Closing the file
file.close()

Explanation:

  1. We use the open() function with the filename "example.txt" and mode "w" (write mode), which creates the file if it does not exist.
  2. The write() method writes a string to the file.
  3. The close() function ensures that the file is properly closed.

Output:

A new file named “example.txt” is created containing the give text to write() function.

2. Writing Multiple Lines to a File

You can write multiple lines to a file using the writelines() method.

In this example, we will use write() method to write a list of strings to a file example.txt.

main.py

</>
Copy
# Opening a file in write mode
file = open("example.txt", "w")

# List of lines to write
lines = ["First line\n", "Second line\n", "Third line\n"]

# Writing multiple lines to the file
file.writelines(lines)

# Closing the file
file.close()

Explanation:

  1. We use writelines() to write multiple lines at once from a list of strings.
  2. Each string in the lines list contains a newline character (\n) to ensure that each line appears separately in the file.
  3. The file is closed after writing to ensure changes are saved.

Output:

The file “example.txt” now contains:

3. Writing Data to a File Using with Statement

The with statement ensures the file is automatically closed after writing.

In this example, we will use with statement to write a string (containing a single line) to a file example.txt.

main.py

</>
Copy
# Using with statement to open file
with open("example.txt", "w") as file:
    file.write("This is written using the with statement.")

# File is automatically closed after exiting the block

Explanation:

  1. The with statement manages file opening and closing automatically.
  2. The write() method writes the text to the file.
  3. No need to call close() explicitly, as Python takes care of it.

Output:

The file “example.txt” now contains:

4. Appending Data to an Existing File

Using append mode ("a"), we can add content to an existing file without overwriting it.

In this example, we will append a string to the file example.txt, which is already created in the previous example.

main.py

</>
Copy
# Opening a file in append mode
with open("example.txt", "a") as file:
    file.write("\nThis is an appended line.")

# File is automatically closed after writing

Explanation:

  1. We open the file in append mode ("a") to add content without erasing existing data.
  2. The write() method adds a new line at the end.
  3. The \n ensures the appended text starts on a new line.

Output:

The file “example.txt” now contains:

5. Writing Data to a File in Binary Mode

Binary mode ("wb") allows writing non-text data such as images or encoded bytes.

In this example, we will write data to a file binary_file.bin in binary mode.

main.py

</>
Copy
# Writing binary data to a file
binary_data = b"Binary content"

with open("binary_file.bin", "wb") as file:
    file.write(binary_data)

Explanation:

  1. The prefix b before the string indicates binary data.
  2. We open the file in binary write mode ("wb").
  3. The write() method stores the binary content in the file.

Output:

A binary file “binary_file.bin” is created containing binary data.

Conclusion

Python provides multiple ways to write data to files:

  1. write(): Writes a single string.
  2. writelines(): Writes multiple lines at once.
  3. with statement: Manages file handling automatically.
  4. Append mode ("a"): Adds new content without overwriting.
  5. Binary mode ("wb"): Writes non-text data.