Write a List to a File in Python

In Python, we can write a list to a file using different methods such as writelines(), a loop with write(), or by converting the list into a formatted string. Depending on the file format, we may need to use additional libraries such as csv or json for structured data storage.


Examples

1. Writing a List to a File Using writelines()

The writelines() method allows writing multiple lines to a file from a list.

</>
Copy
# Creating a list of strings
lines = ["Python\n", "Java\n", "C++\n", "JavaScript\n"]

# Opening the file in write mode and writing the list
with open("programming_languages.txt", "w") as file:
    file.writelines(lines)

print("List written to file successfully.")

Explanation:

Here:

  • lines: A list of programming languages, where each element includes a newline character (\n) to separate them in the file.
  • open("programming_languages.txt", "w"): Opens a file in write mode, creating it if it doesn’t exist.
  • writelines(lines): Writes all elements of the list to the file without adding extra newline characters.
  • with open(...): Ensures the file is properly closed after writing.

Output:

List written to file successfully.

The file programming_languages.txt will contain:

Python
Java
C++
JavaScript

2. Writing a List to a File Using a Loop

Instead of writelines(), we can use a loop with write() to add elements one by one.

</>
Copy
# List of fruits
fruits = ["Apple", "Banana", "Cherry", "Mango"]

# Opening the file and writing each item separately
with open("fruits.txt", "w") as file:
    for fruit in fruits:
        file.write(fruit + "\n")

print("List written to file successfully.")

Explanation:

  • fruits: A list of fruit names.
  • for fruit in fruits: Iterates over each element in the list.
  • file.write(fruit + "\n"): Writes each element to the file with a newline character.

Output:

List written to file successfully.

The file fruits.txt will contain:

Apple
Banana
Cherry
Mango

3. Writing a List to a CSV File

For structured data, we can use the csv module to write a list to a CSV file.

</>
Copy
import csv

# List of student names
students = [["Name", "Age"], ["Arjun", 20], ["Ram", 22], ["Priya", 21]]

# Writing to a CSV file
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(students)

print("List written to CSV file successfully.")

Explanation:

  • students: A list containing sublists (each representing a row in the CSV).
  • csv.writer(file): Creates a CSV writer object.
  • writer.writerows(students): Writes all rows at once.
  • newline="": Prevents extra blank lines in Windows.

Output:

List written to CSV file successfully.

The file students.csv will contain:

Name,Age
Arjun,20
Ram,22
Priya,21

4. Writing a List to a File in JSON Format

To store structured data, we can use the json module.

</>
Copy
import json

# List of dictionaries
employees = [
    {"name": "Arjun", "age": 30},
    {"name": "Ram", "age": 25},
    {"name": "Priya", "age": 35}
]

# Writing to a JSON file
with open("employees.json", "w") as file:
    json.dump(employees, file, indent=4)

print("List written to JSON file successfully.")

Explanation:

  • employees: A list of dictionaries representing employee data.
  • json.dump(employees, file, indent=4): Writes the list to a JSON file with indentation.

Output:

List written to JSON file successfully.

The file employees.json will contain:

[
    {
        "name": "Arjun",
        "age": 30
    },
    {
        "name": "Ram",
        "age": 25
    },
    {
        "name": "Priya",
        "age": 35
    }
]