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.

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()andwritelines(). 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.

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.

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 (?, ?, ?, ?, ?)
""",