DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk2 min

How to Write an Array to a File in Python

Learn when to write Python values as plain text, JSON, or pickle, with examples for saving and reloading lists.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a readable file with one value per line, convert each value to text and write it with a context manager. For a list or nested list you want to reload with its structure intact, use JSON. Pickle can preserve more complex Python objects, but never load a pickle file from an untrusted source.

Write values to a plain-text file

A text file stores characters, so convert each value to a string representation. This example writes one value per line:

values = [10, 20, 30]

with open("array.txt", "w", encoding="utf-8") as f:
    f.writelines(f"{value}n" for value in values)

The context manager closes the file when the block ends, including if an exception occurs. The "w" mode creates the file or replaces its existing contents; encoding="utf-8" makes the text encoding explicit.

This format is easy to inspect, but it does not record the original types or structure. To read it back, your program must know that each line represents one value and convert the text as needed. Python’s tutorial documents that f.write(string) writes a string and returns the number of characters written: Python Tutorial: Reading and Writing Files.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Save a list or nested list as JSON

Use JSON when you want list structure to survive saving and reloading, or when another application may need to read the data. Python’s json module is part of the standard library:

import json

values = [[1, 2], [3, 4]]

with open("array.json", "w", encoding="utf-8") as f:
    json.dump(values, f)

with open("array.json", encoding="utf-8") as f:
    restored = json.load(f)

Here, restored is a Python list with the nested structure. JSON supports common data types such as lists and dictionaries, but it does not automatically serialize every Python object or custom class; those require an appropriate conversion. Python’s tutorial recommends UTF-8 when opening JSON files: Python Tutorial: Saving Structured Data with JSON.

A JSON file is not a sequence of independent documents. Calling json.dump() repeatedly on the same file does not create valid separate JSON values; instead, write one enclosing value or choose a record format designed for multiple records. See the Python JSON library reference.

Choose a file format for your goal

Goal Starting format Trade-off
Inspect values easily Plain text, often one value per line You must define how to parse the lines and restore types.
Keep a list or nested data structured, including for other software JSON Values must be JSON-compatible or converted first.
Restore more complex Python objects Pickle Python-specific, and unsafe to load from an untrusted source.

When pickle is appropriate—and when it is not

Pickle can serialize Python-specific objects that do not fit naturally into JSON. It is not a suitable interchange format for applications written in other languages. More importantly, deserializing an untrusted pickle file can execute arbitrary code. Only load pickle files from sources you trust. Python explains these limitations in its tutorial section on structured data and pickle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What “array” means in this example

Python programmers may use “array” to mean an ordinary list, the standard-library array type, or a NumPy ndarray. The examples here show ordinary Python lists. NumPy arrays may call for NumPy-specific I/O methods, so do not assume these examples cover their storage requirements.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.