How to Write Lines to a File in Python?

In this tutorial, I will explain how to write lines to a file in Python. As a Python developer working on a project for one of my clients, I came across a scenario where I needed to write lines to a file in Python. After researching I found some important methods to achieve this task. I will share my findings in this post with examples.

Write Lines to a File in Python

Let us learn some important methods to write lines to a file in Python.

Read How to Clear a File in Python?

Method 1. Use the write() Method

One way to write lines to a file in Python is by using the write() method. This method allows you to write a string of text to a file. Here’s an example:

with open("customers.txt", "w") as file:
    file.write("John Smith\n")
    file.write("123 Main St, Anytown, USA\n")
    file.write("(555) 123-4567\n")

I executed the above example and added the screenshot below.

Write Lines to a File in Python

In this example, we open a file named customers.txt in write mode ("w") using the with statement. We then use the write() method to write three lines of text to the file, each ending with a newline character (\n). The newline character ensures that each piece of information is on a separate line in the file.

Check out How to Read XML Files in Python?

Method 2. Use the print() Function

Another way to write lines to a file is by using the print() function in Python with the file parameter. This method is useful when you want to write multiple items to a file at once. Here’s an example:

with open("employees.txt", "w") as file:
    print("Emma Johnson", file=file)
    print("Software Engineer", file=file)
    print("New York, NY", file=file)

I executed the above example and added the screenshot below.

How to Write Lines to a File in Python

In this example, we open a file named employees.txt in write mode and use the print() function to write three lines of text to the file. By specifying the file parameter, we tell Python to write the output to the file instead of the console.

Read How to Skip the First Line in a File in Python?

Write Lists to Files in Python

Sometimes you may have a list of items that you want to write to a file, with each item on a separate line. You can achieve this using the writelines() method in Python. Here’s an example:

states = ["California", "Texas", "Florida", "New York", "Illinois"]

with open("states.txt", "w") as file:
    file.writelines(state + "\n" for state in states)

I executed the above example and added the screenshot below.

Write Lines to a File in Python Lists to Files

In this example, we have a list of U.S. states called states. We open a file named states.txt in write mode and use the writelines() method to write each state to the file. We use a generator expression (state + "\n" for state in states) to add a new line character after each state, ensuring that each state is on a separate line in the file.

Check out How to Split a File into Multiple Files in Python?

Append to Existing Files in Python

If you want to add new lines to an existing file without overwriting its contents, you can open the file in append mode ("a"). Here’s an example:

cities = ["Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio"]

with open("cities.txt", "a") as file:
    for city in cities:
        file.write(city + "\n")

In this example, we have a list of U.S. cities called cities. We open a file named cities.txt in append mode and use a for loop to write each city to the file, adding a newline character after each city. If the file already exists, the new lines will be appended to the end of the file without overwriting the existing content.

Read How to Read Tab-Delimited Files in Python?

Handle File Paths

When working with files, it’s important to consider file paths. If the file you want to write to is not in the same directory as your Python script, you’ll need to provide the full path to the file. Here’s an example:

file_path = "/Users/johndoe/Documents/customers.txt"

with open(file_path, "w") as file:
    file.write("Sarah Thompson\n")
    file.write("456 Elm St, Somewhere, USA\n")
    file.write("(555) 987-6543\n")

In this example, we specify the full path to the customers.txt file using the file_path variable. We then use the with statement and the write() method to write lines of text to the file, just like in the previous examples.

Check out How to Unzip a File in Python?

Best Practices for Writing to Files in Python

When writing lines to files in Python, there are a few best practices to keep in mind:

  1. Always close the file after you’re done writing to it. The with statement takes care of this automatically, but if you’re not using with, be sure to call the close() method on the file object.
  2. Use meaningful and descriptive file names that reflect the content of the file. This will make it easier to understand the purpose of the file later on.
  3. Consider using a context manager (the with statement) when working with files. It ensures that the file is properly closed, even if an exception occurs during the writing process.
  4. Be mindful of the file’s encoding. By default, Python uses the system’s default encoding (e.g., UTF-8 on many systems). If you need to use a different encoding, you can specify it when opening the file, like this: open("file.txt", "w", encoding="utf-16").

Read How to Get the File Size in MB using Python?

Conclusion

In this tutorial, I helped you learn how to write lines to a file in Python. I explained some methods such as using the write() method, the print() function with the file parameter, and the writelines() method for writing lists to files. I also discussed appending to existing files and handling file paths along with some best practices.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.