Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Read and Write a List to a File in Python

  • 30 Jul, 2025
  • Com 0
Read and Write List into File

Writing a list to a file

Use the built-in write() or writelines() function for lists of strings to write to a list file.

First, we will open a new file called stocks.txt using with open() statement in writing mode (“w”). While the file is open, use a for loop to iterate through each list element and write to that file.

stocks = ['Kaynes', 'V2', 'Polycab']

with open('stocks.txt', 'w') as f:
    for stock in stocks:
        f.write(f"{stock}\n")  # \n ensures each item is on a new line

print("Stocks list has been written to stocks.txt")

# Output: Stocks list has been written to stocks.txt

List written in a file

Using writelines() (For Pre-Formatted Lines)

If you are working with large lists and they require manual newline handling, always use the built-in writelines() method.

numbers = ['1\n', '2\n', '3\n']  # Newlines must be included

with open('numbers.txt', 'w') as f:
    f.writelines(numbers)  # No automatic newlines!

print("Numbers list has been written to numbers.txt")

# Output: Numbers list has been written to numbers.txt

Using writelines() to write a list into a file

Writing a list to a JSON file

The file opening and writing process is the same, but to write JSON, use the json.dump() method.

It preserves nested structures and data types (int, float, bool, etc.).

import json

# List to be saved as JSON
data = [1, "hello", True, {"key": "value"}]

# Save the list to a JSON file
with open('data.json', 'w') as f:
    json.dump(data, f)

Written json data

Writing a list to a CSV file

What if we want to save a list as a csv file? Well, in that case, we need to import the built-in csv module and use csv.writer() method to write a list data in the CSV file.

import csv

data = [["stocks", "price"], ["Kaynes", 5638], ["V2Retail", 1956]]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)  # Write all rows at once

print("CSV file created successfully from list of lists.")

# Output: CSV file created successfully from list of lists

list to csv file

Empty list

What if the list does not contain any element? Well, it won’t create an output file since there is nothing to write.

empty_list = []

with open("empty.txt", "w") as file:
    for item in empty_list:
        file.write(f"{item}\n")
        print(f"Written item: {item}")

if not empty_list:
    print("The list is empty. No items were written.")

# Output: The list is empty. No items were written.

Reading a list from a file

You can read a list from a text file and print it as a string using the .readlines() method. If you want to remove newlines, apply the .strip() function using list comprehension.

We have already created a file stocks.txt. Let’s read that file and print it as a list in the console.

with open("stocks.txt", "r") as file:
    stocks = file.readlines()  # Reads all lines into a list
    stocks = [element.strip() for element in stocks]  # Remove newlines

print(stocks)

# Output: ['Kaynes', 'V2', 'Polycab']

Reading a list from a CSV file

There is a built-in csv module that provides csv.reader() method, which helps us read a CSV file and convert the data into a list of lists using the list() method.

import csv

with open("data.csv", "r", newline="") as file:
    reader = csv.reader(file)
    data = list(reader)  # Convert to list of lists

print(data)

# Output: [['stocks', 'price'], ['Kaynes', '5638'], ['V2Retail', '1956']]

You can see that the output is a list of lists, where each inner list is a row.

Reading a list from a JSON file

To read a JSON file, use the built-in json.load() method that returns a list of dictionaries. The json.load() method deserializes JSON into Python objects.

We already have a data.json file, which we will read.

import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)

# Output: [1, 'hello', True, {'key': 'value'}]

Empty file

If the file is empty and does not contain any elements, the output list will be empty too!

with open("empty.txt", "r") as file:
    lines = [line.strip() for line in file]

print(lines)

# Output: []

That’s all!

Post Views: 45
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Create an Empty File in Python
How to Split a List in Python

Leave a Reply Cancel reply

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

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend