How to Write an Array to a File in Python

I built a leave-tracking script for a 10-person marketing team in Austin, Texas. The team had tracked vacation days in a shared Excel sheet for years. Someone always forgot to save it, and someone else overwrote a formula. The HR lead finally asked for something sturdier.

I replaced that fragile process with a small local Python app backed by SQLite, a lightweight file-based database that ships with Python. The app pulls employee names, leave types, and dates into memory, then saves that data outside the program. That is where you write an array to a file in Python, the core skill this article covers.

You will learn five distinct ways to do it: plain text, CSV, JSON, NumPy’s savetxt, and pickle for binary data. Each method fits a different job, and you will see real code with real output for every one.

What Counts as an Array in Python?

Python does not have a built-in array type the way C or Java does. Instead, Python developers commonly use the list, a built-in ordered collection that can hold mixed data types, as their everyday array.

employees = ["Maria Gomez", "Liam Chen", "Priya Patel", "Jordan Smith"]
print(type(employees))

Output:

<class 'list'>

Lists are flexible and easy to write. For the leave-tracking app, a list works perfectly for employee names or leave dates.

Python also includes an array module in its standard library. It creates arrays that hold only one data type, which saves memory for large numeric datasets. Most beginners skip it because lists handle most everyday tasks.

Then there is the NumPy array from the third-party NumPy library. NumPy arrays support fast math operations, multiple dimensions, and specialized file formats. If your app calculates average PTO usage, a NumPy array provides a better tool. You can learn more from these guides about creating Python arrays and converting a list to an array.

This Python tutorial covers both regular lists and NumPy arrays. Here is the project structure used throughout the examples:

leave_tracker/
├── leave_tracker.db
├── employees.txt
├── leave_requests.csv
├── leave_balances.json
├── pto_days_used.csv
├── leave_calendar.pkl
└── app.py

Every example assumes Python 3.11 or later running locally on Windows, macOS, or Linux. You do not need a cloud service or complex project structure.

Method 1: Writing a List to a Plain Text File

Plain text offers the simplest format. Use it when you need a readable list, such as an employee roster for a manager.

Python’s built-in open() function creates or opens a file. The with statement is a context manager. It automatically closes the file when the code block finishes, even if an error occurs.

employees = ["Maria Gomez", "Liam Chen", "Priya Patel", "Jordan Smith"]

with open("employees.txt", "w") as file:
file.write("\n".join(employees))

with open("employees.txt", "r") as file:
print(file.read())

Output:

Maria Gomez
Liam Chen
Priya Patel
Jordan Smith

I executed the above example code and added the screenshot below.

Write an Array to a File in Python

Here, "\n".join(employees) joins the list items with a newline character. The write() method sends the resulting string to the file in one operation.

Why use this: It needs no extra libraries and produces a file anyone can open in a text editor.

When to use it: Choose plain text for short lists, logs, and exports that do not require columns.

Limitation: Plain text provides no built-in structure. Leave records with several fields per line quickly become difficult to manage.

For lists where each item already contains a line break, writelines() works better than write() with join().

leave_days = ["2026-07-21\n", "2026-07-22\n", "2026-07-23\n"]

with open("maria_leave_dates.txt", "w") as file:
file.writelines(leave_days)

with open("maria_leave_dates.txt", "r") as file:
print(file.read())

Output:

2026-07-21
2026-07-22
2026-07-23

writelines() writes each string one after another without adding separators. You must include the newline character (\n) in each item yourself. Otherwise, all values appear on one line.

Pro Tip: I always check whether my list items already contain newline characters before choosing between write() and writelines(). Mixing them up often creates unreadable text files.

Method 2: Writing an Array to a CSV File

CSV means comma-separated values. It gives your array rows and columns that spreadsheet applications can read. This format works well when HR needs an Excel-friendly leave report.

Python’s built-in csv module handles formatting details such as commas inside text fields. You do not need to build that logic yourself.

import csv

leave_requests = [
["employee", "leave_type", "start_date", "end_date", "status"],
["Maria Gomez", "PTO", "2026-07-21", "2026-07-23", "approved"],
["Liam Chen", "Sick", "2026-07-20", "2026-07-20", "approved"],
["Priya Patel", "PTO", "2026-08-03", "2026-08-07", "pending"],
]

with open("leave_requests.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(leave_requests)

with open("leave_requests.csv", "r") as file:
print(file.read())

Output:

employee,leave_type,start_date,end_date,status
Maria Gomez,PTO,2026-07-21,2026-07-23,approved
Liam Chen,Sick,2026-07-20,2026-07-20,approved
Priya Patel,PTO,2026-08-03,2026-08-07,pending

I executed the above example code and added the screenshot below.

How to Write an Array to a File in Python

This example uses a 2D array, which means a list containing other lists. Each inner list represents one row. The writerows() method loops through the outer list and writes every inner list.

Notice the newline="" argument. Without it, Windows systems may add unwanted blank lines between CSV rows.

Why use this: CSV provides a standard format that spreadsheets and many data tools understand.

When to use it: Choose CSV for tabular data with consistent columns, including leave requests, timesheets, and attendance logs.

Limitation: CSV stores everything as text. Code reading the file must convert dates and numbers back into their correct data types.

You can later load the export for analysis by reading CSV files with NumPy. For larger tabular datasets, this guide to working with CSV files in pandas covers another practical option.

Method 3: Writing an Array to a JSON File

JSON means JavaScript Object Notation. It stores structured data as readable text. It works well when your array contains dictionaries. The leave-tracking app might store each employee’s remaining PTO balance this way.

Python’s built-in json module converts Python data structures directly into JSON text.

import json

leave_balances = [
{"employee": "Maria Gomez", "pto_days_left": 12},
{"employee": "Liam Chen", "pto_days_left": 8},
{"employee": "Priya Patel", "pto_days_left": 15},
]

with open("leave_balances.json", "w") as file:
json.dump(leave_balances, file, indent=2)

with open("leave_balances.json", "r") as file:
print(file.read())

Output:

[
{
"employee": "Maria Gomez",
"pto_days_left": 12
},
{
"employee": "Liam Chen",
"pto_days_left": 8
},
{
"employee": "Priya Patel",
"pto_days_left": 15
}
]

I executed the above example code and added the screenshot below.

Write an Array to File in Python

The json.dump() function writes the data directly to the open file. The indent=2 argument adds two-space indentation, making the output easier to read. Removing that argument produces one compact line.

Why use this: JSON preserves nested lists and dictionaries, so it retains the original structure.

When to use it: Choose JSON for mixed data types, nested details, configuration files, or data another application will consume.

Limitation: JSON has no native date type. It stores dates as strings, so Python must parse them before performing date calculations.

For example, HR often needs the inclusive duration of a PTO request. The datetime module turns each date string into a date object, which represents a calendar date Python can calculate with.

from datetime import datetime

start_text = "2026-07-21"
end_text = "2026-07-23"

start_date = datetime.strptime(start_text, "%Y-%m-%d").date()
end_date = datetime.strptime(end_text, "%Y-%m-%d").date()
duration = (end_date - start_date).days + 1

print(f"PTO duration: {duration} days")

Output:

PTO duration: 3 days

The strptime() function parses each string using the YYYY-MM-DD pattern. Adding one counts both dates, which matches many U.S. leave policies. A production app should also exclude weekends and company holidays when its policy requires that.

Method 4: Writing a NumPy Array to a File with savetxt

Suppose the leave app calculates how many PTO days each employee used this year. It can store those counts in a NumPy array for fast averages and other calculations.

NumPy does not come with Python. Install it from your command line:

pip install numpy

Output:

Successfully installed numpy

Your version number may differ. You can then use numpy.savetxt(), a function designed specifically for writing numeric arrays to text files.

import numpy as np

pto_days_used = np.array([3, 5, 2, 7, 4, 6, 1, 8, 3, 5])

np.savetxt(
"pto_days_used.csv",
pto_days_used,
delimiter=",",
fmt="%d",
header="pto_days_used",
comments=""
)

with open("pto_days_used.csv", "r") as file:
print(file.read())

Output:

pto_days_used
3
5
2
7
4
6
1
8
3
5

The fmt="%d" argument writes each value as a whole integer instead of a decimal. The header argument adds a label, while comments="" removes NumPy’s default # character.

The guide to NumPy’s savetxt function explains more formatting options. You can also review the broader introduction to Python NumPy arrays.

Why use this: The function handles numeric formatting, delimiters, and headers in one call.

When to use it: Choose savetxt() for numeric data used in analysis, including multi-dimensional attendance or PTO arrays.

Limitation: savetxt() works best with numeric data. Mixing employee names with numbers requires extra formatting, making regular CSV or JSON more practical.

Method 5: Writing an Array to a Binary File with Pickle

Sometimes you need to save a Python object without converting it to text. Python’s built-in pickle module handles that job.

Pickle serializes an object, meaning it converts the object into a stream of bytes. It can preserve lists, tuples, dictionaries, and custom objects.

Suppose the leave app builds a leave calendar as a list of tuples. Pickle lets the app save and reload that data without parsing CSV or JSON.

import pickle

leave_calendar = [
("Maria Gomez", "2026-07-21", "2026-07-23"),
("Liam Chen", "2026-07-20", "2026-07-20"),
("Priya Patel", "2026-08-03", "2026-08-07"),
]

with open("leave_calendar.pkl", "wb") as file:
pickle.dump(leave_calendar, file)

with open("leave_calendar.pkl", "rb") as file:
loaded_calendar = pickle.load(file)

print(loaded_calendar)

Output:

[('Maria Gomez', '2026-07-21', '2026-07-23'), ('Liam Chen', '2026-07-20', '2026-07-20'), ('Priya Patel', '2026-08-03', '2026-08-07')]

The "wb" mode writes binary data, while "rb" reads binary data. Opening a pickle file in a text editor displays unreadable characters.

Why use this: Pickle preserves the exact Python object, including tuples, nested structures, and custom classes.

When to use it: Choose pickle for internal caching between runs of your own Python application.

Limitation: Other programming languages cannot easily read pickle files. Never load a pickle file from an unknown source because malicious files may execute unwanted code.

Exporting a SQLite Array to a File in Python

The team stores its leave requests in a local SQLite database. A database organizes data so the application can search, update, and manage it reliably.

The app can fetch rows into a Python array and export them to CSV for HR.

import sqlite3
import csv

connection = sqlite3.connect("leave_tracker.db")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS leave_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
employee TEXT NOT NULL,
leave_type TEXT NOT NULL,
start_date TEXT NOT NULL,
end_date TEXT NOT NULL,
status TEXT NOT NULL
)
""")

cursor.execute(
"""
INSERT INTO leave_requests
(employee, leave_type, start_date, end_date, status)
VALUES (?, ?, ?, ?, ?)
""",
("Jordan Smith", "PTO", "2026-08-10", "2026-08-14", "pending")
)

connection.commit()

cursor.execute("""
UPDATE leave_requests
SET status = 'approved'
WHERE employee = 'Jordan Smith'
""")

connection.commit()

cursor.execute("""
SELECT employee, leave_type, start_date, end_date, status
FROM leave_requests
""")

rows = cursor.fetchall()

with open("leave_requests_export.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow([
"employee",
"leave_type",
"start_date",
"end_date",
"status"
])
writer.writerows(rows)

connection.close()

with open("leave_requests_export.csv", "r") as file:
print(file.read())

Output:

employee,leave_type,start_date,end_date,status
Jordan Smith,PTO,2026-08-10,2026-08-14,approved

The CREATE TABLE statement creates the storage structure if it does not exist. The question marks in the INSERT query act as safe placeholders for values.

The example inserts a request, approves it, and lists all available requests. These actions represent part of CRUD operations, meaning create, read, update, and delete operations.

The cursor.fetchall() call returns the query results as a list of tuples. From there, writerows() writes the complete array to the CSV file.

A larger application could place its database and export code into separate Python modules. A module is simply a Python file containing reusable code. For a small beginner Python project, keeping everything in app.py makes testing easier.

Things to Keep in Mind

  • Close files properly: Use the with statement so Python closes each file automatically, even after an error.
  • Match the mode to the format: Use text modes such as "w" and "r" for strings. Pickle and other byte formats require "wb" and "rb".
  • Protect existing files: Opening a file in "w" mode immediately replaces its contents. Follow a safe pattern for checking whether a file exists before overwriting important exports.
  • Handle file errors: Full disks, missing folders, and permission problems can stop your script. Use try and except blocks based on these examples for catching multiple Python exceptions.
  • Build portable paths: Windows and macOS use different path styles. Python’s pathlib module creates paths that work across operating systems. This guide explains how to convert a string to a Path.
  • Match the format to the next step: Choose CSV for spreadsheets, JSON for nested data, pickle for Python-only caching, and savetxt() for numeric analysis.

Frequently Asked Questions

How do I write a list to a text file in Python?

Open the file in write mode with open("file.txt", "w"). Use file.write() with a joined string, or use file.writelines() when each item already contains a newline character.

What is the difference between a Python list and a NumPy array?

A Python list can hold mixed data types and grow dynamically. A NumPy array normally holds one data type and supports fast mathematical operations across large datasets.

Can I write a 2D array to a CSV file?

Yes. Create a list of lists where each inner list represents one row. Pass the complete structure to csv.writer().writerows() to write all rows.

Why does my pickle file look like garbled text?

Pickle stores objects in binary format rather than plain text. Read the file with pickle.load() using "rb" mode instead of opening it in a text editor.

Is JSON better than CSV for saving arrays?

JSON works better for nested structures and mixed data types. CSV works better for flat, tabular data that employees need to open in a spreadsheet.

Do I need NumPy installed to write arrays to a file?

You do not need NumPy for regular Python lists. Install NumPy only when you use NumPy arrays or functions such as numpy.savetxt().

Writing an array to a file turns temporary program data into information your team can share and reload. Choose the format that matches your next step, with CSV serving as the best general option for business data. I hope you found this article helpful.

You May Also Like

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.