How to Write a List to a File in Python?

write list to a file python

In this article, you’ll learn various methods to write a list to a file in Python. Whether you want to save a list to a text file or organize it in a CSV file, we’ll cover all the techniques step by step.

Writing a List to a Text File

Let’s look at the common ways to write a list in a plain text file.

Method 1: Writing Line by Line

Sometimes you need to write each list element as a new line in the file. For example, if you have a shopping list and want to store each item on its own line, this method is ideal.

Example Code

In this example code, the open function opens the file in write mode. The with statement ensures the file is closed properly, even if an error occurs. Inside the with block, a loop writes each item from my_list to the file, appending \n to place each item on a new line.

# List of items
my_list = ["apple", "banana", "cherry"]

# Open a file in write mode
with open("output.txt", "w") as file:
    for item in my_list:
        file.write(item + "\n")  # Add a newline after each item

print("List written to output.txt successfully!")

Output

After running the code, if you open the output.txt file, it will contain:

apple
banana
cherry

Method 2: Writing the Entire List at Once

If you prefer to write the whole list to the file in a single step, then this method is for you. Instead of writing line by line, the list is joined into a single string where each element is separated by a delimiter, such as a newline character.

Example Code

Here, the join method combines all elements of the list into a single string, with each element separated by a newline (\n). This string is then written in one go into the file. The open function, along with the with statement, handles the file operation just like in the previous method.

# List of items
my_list = ["apple", "banana", "cherry"]

# Open a file in write mode
with open("output.txt", "w") as file:
    file.write("\n".join(my_list))

print("List written to output.txt successfully!")

Output

After executing the code, the output.txt file will contain the same result:

apple
banana
cherry

Method 3: Appending to a Text File

There are cases when you don’t want to overwrite a file but instead add new data to it. For example, if you’re maintaining a daily journal or a running log, appending new entries is more practical.

Example Code

In the code below, When the file is opened in append mode (a), Python ensures that any new data is added to the end of the existing content without overwriting it. The for loop works just like in the first method.

# List of items
my_list = ["date", "elderberry", "fig"]

# Open a file in append mode
with open("output.txt", "a") as file:
    for item in my_list:
        file.write(item + "\n")

print("List appended to output.txt successfully!")

Output

If the file output.txt initially contained:

apple
banana
cherry

After running the code, it will look like this:

apple
banana
cherry
date
elderberry
fig

Writing a List to a CSV File

You can use Python’s built-in module csv to save a list to a CSV file. Let’s explore the techniques to store your lists in a CSV format.

If you’re managing tabular data across files, combining multiple CSV files can simplify your workflow.

Method 1: Writing a Single Row

Writing a list to a CSV file is similar to writing to a text file, but it’s more structured. Each element in the list becomes a cell in a single row of the CSV file.

Example Code

In this example code, the csv.writer object prepares the file for CSV writing. Then, the writer.writerow method writes the entire list as a single row in the CSV file.

Here, the newline="" argument ensures that no extra blank lines are added, a common issue on Windows systems.

import csv

# List of items
my_list = ["apple", "banana", "cherry"]

# Open a CSV file in write mode
with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(my_list)

print("List written to output.csv successfully!")

Output

The resulting output.csv file will contain:

apple,banana,cherry

Method 2: Writing Multiple Rows from a Nested List

If you have a nested list (a list of lists), each sublist can represent a row in a CSV file. For instance, this is useful when you’re working with structured data (tabular data).

Example Code

As seen in the code below, the writer.writerows method writes all the rows at once. Each sublist in nested_list becomes a row in the CSV file. The purpose of the newline="" argument is as same as in the first method.

import csv

# Nested list
nested_list = [
    ["Name", "Age", "City"],
    ["Alice", "25", "New York"],
    ["Bob", "30", "San Francisco"],
    ["Charlie", "35", "Chicago"]
]

# Open a CSV file in write mode
with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(nested_list)  # Write all rows at once

print("Nested list written to output.csv successfully!")

Output

After running the code, the output.csv file will look like this:

Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago

For handling structured data, understanding scientific notation in Python can be useful when working with numerical datasets.

Method 3: Writing with a Custom Delimiter

By default, a CSV file uses commas to separate values. However, sometimes you might want to use a different delimiter, such as tabs or semicolons. This can be helpful when dealing with non-standard CSV formats.

Example Code

Here, the csv.writer function uses the delimiter argument to set the character that separates values. The writer.writerow method saves the list as one row, with values separated by semicolons (;).

import csv

# List of items
my_list = ["apple", "banana", "cherry"]

# Open a CSV file with a semicolon delimiter
with open("output_semicolon.csv", "w", newline="") as file:
    writer = csv.writer(file, delimiter=";")
    writer.writerow(my_list)

print("List written to output_semicolon.csv successfully!")

Output

The resulting output_semicolon.csv file will contain:

apple;banana;cherry

Method 4: Appending to a CSV File

Similar to text files, you can also append data to an existing CSV file. This is helpful when you want to add new rows without overwriting the existing content.

Example Code

In this code, the file is opened in append mode (a) to ensure existing content isn’t overwritten. Then, the writer.writerows method adds the new rows to the end of the file.

import csv

# List of items to append
new_rows = [
    ["David", "40", "Los Angeles"],
    ["Eve", "28", "Boston"]
]

# Open the file in append mode
with open("output.csv", "a", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(new_rows)  # Append rows to the existing file

print("Rows appended to output.csv successfully!")

Output

If the initial output.csv file contained:

Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago

After appending, the file will look like this:

Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago
David,40,Los Angeles
Eve,28, Boston

Why Do We Need to Write a List to a File?

There are several reasons to save a Python list to files. Common ones include:

  • Data Persistence: Even after the program stops running, the data is saved permanently.
  • Sharing Information: Files make it easy to share data with others or transfer it between systems.
  • Backup and Recovery: Storing data in files provides a reliable way to back up important information for future use.
  • Cross-Application Compatibility: Files, especially CSVs, allow data to be used in other applications like spreadsheets or databases.
  • Organization: Writing data to files helps structure information, making it easier to retrieve, analyze, or modify later.

Conclusion

You’ve now learned several methods to write a list to a file in Python. Whether it’s a plain text file or a CSV file, you can choose the method that best suits your needs. For simple tasks, writing line-by-line works well. For structured data, the CSV format provides flexibility and scalability. With these techniques, you’re well-equipped to handle data-saving tasks in your Python projects.

If you’re looking for more beginner-friendly articles on Python programming with easy-to-understand analogies, be sure to explore our Python tutorial series at Syntax Scenarios.

Leave a Comment

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

Scroll to Top