Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Write a List Content to a File using Python?
In this article, we will show you how to write list data to a text file using Python. There are several methods to accomplish this task, each with different formatting options.
Writing List Elements Line by Line
The most common approach is to write each list element on a separate line using a loop ?
# Input list
input_list = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']
# Write list elements to file (one per line)
with open("ListDataFile.txt", 'w') as filedata:
for item in input_list:
filedata.write(f"{item}\n")
# Read and display the file contents
with open("ListDataFile.txt", 'r') as filedata:
print(filedata.read())
This is a TutorialsPoint sample file
Using join() Method
A more efficient approach is to use the join() method to concatenate all elements ?
# Input list
input_list = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']
# Write using join() method
with open("ListDataFile.txt", 'w') as filedata:
filedata.write('\n'.join(input_list))
# Read and display the file contents
with open("ListDataFile.txt", 'r') as filedata:
print(filedata.read())
This is a TutorialsPoint sample file
Writing as Space-Separated Values
You can also write all elements on a single line separated by spaces ?
# Input list
input_list = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']
# Write as space-separated values
with open("ListDataFile.txt", 'w') as filedata:
filedata.write(' '.join(input_list))
# Read and display the file contents
with open("ListDataFile.txt", 'r') as filedata:
print(filedata.read())
This is a TutorialsPoint sample file
Writing Mixed Data Types
When your list contains different data types, convert them to strings first ?
# Mixed data types list
mixed_list = ['Python', 3.9, 2024, True, 'Tutorial']
# Convert all elements to strings and write
with open("MixedDataFile.txt", 'w') as filedata:
for item in mixed_list:
filedata.write(f"{str(item)}\n")
# Read and display the file contents
with open("MixedDataFile.txt", 'r') as filedata:
print(filedata.read())
Python 3.9 2024 True Tutorial
Comparison of Methods
| Method | Performance | Best For |
|---|---|---|
| Loop with write() | Slower | Complex formatting needs |
| join() method | Faster | Simple string lists |
| Space-separated | Fastest | Single-line output |
Conclusion
Use join() method for better performance when writing string lists to files. The loop approach offers more flexibility for complex formatting requirements. Always use context managers (with statement) to ensure proper file handling.
