As a data scientist working on various projects across the USA, I came across a scenario where I needed to write multiple lines to a file in Python. After exploring more on this topic I found several methods to accomplish this task. Let us learn more about writing multiple lines to file with examples.
Write Multiple Lines to a File in Python
Imagine you’re working on a project that involves processing a large dataset of customer information for a company based in the United States. You need to extract specific details from the dataset and write them to a file in a structured manner. Each line in the file should represent a single customer’s information. How can you achieve this using Python?
Read How to Write Lines to a File in Python?
Solution 1: Use the write() Method in a Loop
One simple approach to writing multiple lines to a file is to use the Python write() method in a loop. Here’s an example:
# Customer data
customers = [
{"name": "John Smith", "email": "john.smith@example.com", "country": "USA"},
{"name": "Emma Johnson", "email": "emma.johnson@example.com", "country": "USA"},
{"name": "Michael Brown", "email": "michael.brown@example.com", "country": "USA"}
]
# Open the file in write mode
with open("customers.txt", "w") as file:
# Iterate over each customer
for customer in customers:
# Write the customer's information to the file
file.write(f"{customer['name']},{customer['email']},{customer['country']}\n")I executed the above code and added the screenshot below.

In this example, we have a list of dictionaries called customers, where each dictionary represents a customer’s information. We open the file customers.txt in write mode using the with statement, which ensures that the file is properly closed after writing.
Inside the with block, we iterate over each customer dictionary using a for loop. For each customer, we write their information (name, email, and country) to the file using the write() method. We separate the values with commas and add a new line character \n at the end of each line to start a new line for the next customer.
Check out How to Clear a File in Python?
Solution 2: Use the writelines() Method
Another efficient way to write multiple lines to a file is by using the writelines() method. This method takes an iterable (such as a list) of strings and writes each string as a separate line to the file. Here’s an example:
# Customer data
customers = [
"Sarah Davis,sarah.davis@example.com,USA\n",
"David Wilson,david.wilson@example.com,USA\n",
"Olivia Thompson,olivia.thompson@example.com,USA\n"
]
# Open the file in write mode
with open("customers.txt", "w") as file:
# Write the lines to the file
file.writelines(customers)I executed the above code and added the screenshot below.

In this example, we have a list called customers that contains the customer information as strings. Each string represents a line to be written to the file, with the values separated by commas and ending with a newline character.
We open the file customers.txt in write mode using the with statement. Inside the with block, we use the writelines() method to write all the lines from the customers list to the file in a single call.
Read How to Read XML Files in Python?
Append Lines to an Existing File in Python
In some cases, you may want to append new lines to an existing file instead of overwriting its contents. To accomplish this, you can open the file in append mode by passing the mode argument as "a" instead of "w". Here’s an example:
# Additional customer data
new_customers = [
"Robert Anderson,robert.anderson@example.com,USA\n",
"Jennifer Taylor,jennifer.taylor@example.com,USA\n"
]
# Open the file in append mode
with open("customers.txt", "a") as file:
# Append the new lines to the file
file.writelines(new_customers)I executed the above code and added the screenshot below.

In this example, we have a list called new_customers that contains additional customer information. We open the file customers.txt in append mode using "a". Inside the with block, we use the writelines() method to append the new lines to the existing file.
Check out How to Skip the First Line in a File in Python?
Handle File Paths
When working with files, it’s important to handle file paths correctly. Python provides the os module, which offers various functions for working with file paths. Here’s an example of how to handle file paths:
import os
# File path
file_path = os.path.join("data", "customers.txt")
# Open the file in write mode
with open(file_path, "w") as file:
# Write lines to the file
file.writelines(customers)In this example, we use the os.path.join() function to create a file path by joining the directory "data" and the file name "customers.txt". This ensures that the file path is constructed correctly regardless of the operating system.
Read How to Split a File into Multiple Files in Python?
Best Practices and Tips
When writing multiple lines to a file in Python, keep the following best practices and tips in mind:
- Always close the file after writing to ensure that the data is properly saved and to free up system resources. Using the
withstatement takes care of this automatically. - Choose the appropriate file mode based on your requirements. Use
"w"for writing (overwriting existing content) or"a"for appending to an existing file. - Use meaningful and descriptive file names that reflect the contents of the file.
- Handle file paths using the
osmodule to ensure cross-platform compatibility. - Consider using the
csvmodule when working with comma-separated values (CSV) files for more advanced functionality and proper handling of special characters.
Check out How to Read Tab-Delimited Files in Python?
Conclusion
In this article, I helped you learn how to write multiple lines to a file in Python. I explained using the write() method in a loop, and the writelines() method. I also discussed how to append lines to an existing file in Python, best practices, and handling file paths correctly.
You may like to read:
- How to Check If a File Exists and Create It If Not in Python?
- How to Get the File Size in MB using Python?
- How to Unzip a File in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.