Club.noww.in
Recently, one Python developer asked me about writing a list to a file in Python. I suggested different methods. In this tutorial, I will explain, how to write lists to files in Python with examples.
Python Write List to File
Now, let me show you how to write a list to file in Python using different methods with examples.
Method 1: Write a List to a File Using write()
The simplest way to write a list to a file is by using the write() method in Python. This method involves converting the list to a string before writing it to the file.
Syntax:
Here is the syntax:
file.write(string)- file: The file object you’re writing to.
- string: The string representation of the list.
Example:
Here is an example:
# Define a list names = ["Alice Johnson", "Bob Smith", "Charlie Brown"] # Open a file in write mode with open("names.txt", "w") as file: # Convert list to string and write to file file.write("\n".join(names))In this example, we have a list of names, and we write each name to a new line in the file names.txt.
Here is the exact output in the screenshot below:
Check out How to Iterate Through a List in Python?
Method 2: Using writelines()
The writelines() method can be used to write a list to a file in Python directly. This method is more efficient for writing lists as it doesn’t require converting the list to a string first.
Syntax:
Here is a syntax:
file.writelines(list)- file: The file object you’re writing to.
- list: The list of strings to write.
Example:
You can see an example:
# Define a list cities = ["New York\n", "Los Angeles\n", "Chicago\n"] # Open a file in write mode with open("cities.txt", "w") as file: # Write list to file file.writelines(cities)Here, the list cities is written to cities.txt, with each city on a new line.
Here is the output in the screenshot below:
Read Convert String to List in Python Without Using Split
Method 3: Using csv.writer()
For lists that represent tabular data, the csv.writer() method from the csv module is a great option.
Syntax:
Here is the syntax:
csv_writer.writerow(list)- csv_writer: A csv.writer object.
- list: The list of items to write as a row.
Example:
Here is an example:
import csv # Define a list of lists data = [ ["Name", "Age", "City"], ["Alice Johnson", 30, "New York"], ["Bob Smith", 25, "Los Angeles"], ["Charlie Brown", 35, "Chicago"] ] # Open a file in write mode with open("people.csv", "w", newline='') as file: writer = csv.writer(file) # Write each list as a row writer.writerows(data)In this example, we write a list of lists to people.csv, creating a CSV file with headers and rows of data.
Method 4: Using json.dump()
For more complex data structures, including lists of dictionaries, the json.dump() method from the json module is ideal.
Syntax:
Here is the syntax:
json.dump(list, file)- json: The json module.
- list: The list to write.
- file: The file object to write to.
Example:
Here is an example:
import json # Define a list of dictionaries people = [ {"name": "Alice Johnson", "age": 30, "city": "New York"}, {"name": "Bob Smith", "age": 25, "city": "Los Angeles"}, {"name": "Charlie Brown", "age": 35, "city": "Chicago"} ] # Open a file in write mode with open("people.json", "w") as file: # Write list to file json.dump(people, file, indent=4)Here, we write a list of dictionaries to people.json, with each dictionary representing a person’s details.
Here is the exact output in the screenshot below:
Check out Convert String to List in Python
Python Write List to File with Newline
Let me show you how to write lists to file with a newline in Python using different methods.
Method 1: Using write() with Newline Characters
One of the best ways to write a list to a file with each item on a new line is by using the write() method along with newline characters (\n).
Example:
Let me show you an example:
# Define a list names = ["Alice Johnson", "Bob Smith", "Charlie Brown"] # Open a file in write mode with open("names_newline.txt", "w") as file: for name in names: file.write(name + "\n")In this example, we iterate through the list names and write each name to names_newline.txt, appending a newline character (\n) to ensure each name appears on a new line.
Here is the output in the screenshot below:
Method 2: Using writelines() with Newline Characters
The writelines() method can also be used to write a list to a file in Python. However, you need to ensure that each item in the list ends with a newline character.
Example:
Here is an example:
# Define a list with newline characters included cities = ["New York\n", "Los Angeles\n", "Chicago\n"] # Open a file in write mode with open("cities_newline.txt", "w") as file: file.writelines(cities)Here, the list cities already contains newline characters, so writelines() writes each city to a new line in cities_newline.txt.
Read Merge Lists Without Duplicates in Python
Method 3: Using List Comprehension with writelines()
You can combine list comprehension with writelines() to add newline characters dynamically.
Example:
Let me show you an example.
# Define a list fruits = ["Apple", "Banana", "Cherry"] # Open a file in write mode with open("fruits_newline.txt", "w") as file: file.writelines([fruit + "\n" for fruit in fruits])In this example, we use list comprehension to append a newline character to each item in the list fruits before writing it to fruits_newline.txt.
Method 4: Using print() with File Argument
The print() function can also be used to write to a file, with each call to print() automatically adding a newline character.
Example:
Here is an example.
# Define a list states = ["California", "Texas", "Florida"] # Open a file in write mode with open("states_newline.txt", "w") as file: for state in states: print(state, file=file)In this example, we use print() to write each state to states_newline.txt. The print() function adds a newline character by default.
Conclusion
In this tutorial, I explained how to write a list to a file in Python using different methods. I also explained how to write list to file with newline in Python.
You may also like: