Fundamentals 5 min read

How to Export Multiple Python Lists to a Text File with Simple Code

This article walks through a community question about saving several mixed-type Python lists to a txt file, presenting three code solutions—including direct writes, global variable iteration, and a concise eval loop—while comparing their flexibility and suitability.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Export Multiple Python Lists to a Text File with Simple Code

Introduction

In a Python community a user asked how to save several lists with mixed numeric and string values into a txt file. The article shares multiple solutions.

Problem

Given lists such as lst_1 = ['a1', 2300, 1300] ... lst_5 = ['a6', 39000, 157, 'a8', 3000, 127], the goal is to write each list to a file, preferably only the list values without extra variable names.

Solution 1 – Direct write

with open('txtxtx.txt', 'a+', encoding='utf-8') as f:
    f.write(f"{['a1',2300,1300]}
")

This writes a single list; a loop can be added to handle all lists.

Solution 2 – Using globals() and eval

with open('test-18.txt', 'w+') as f:
    for key in list(globals()):
        if key.startswith("lst_"):
            f.write(f'{eval(key)}
')

This iterates over global variables whose names start with lst_ and writes their evaluated values.

Solution 3 – Simple loop with eval

data = ''
count = 6  # number of lists + 1
for i in range(1, count):
    s = eval(f'lst_{i}')
    data += f'{s}
'
with open('test-19.txt', 'w+', encoding='utf-8') as f:
    f.write(data)

This method builds a string of all list contents and writes it at once; it works when list names follow a regular pattern.

Conclusion

The article demonstrates three ways to export multiple Python lists to a text file, comparing their flexibility and suitability for different naming conventions.

PythonFile I/Oevallist processing
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.