October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Write Multiple Lines to a File in Python

Use a multiline string with write(), or pass separate strings to writelines() after adding the newline characters yourself. Choose "w" to overwrite and "a" to append.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For ordinary text, write a string containing n newline characters inside a with open(...) block. Use "w" to replace a file or "a" to add to it, and specify UTF-8 explicitly.

Write multiple lines from one string

If your content is already a multiline string, pass it to write(). Python writes the string as given; the newline characters separate its lines.

with open("output.txt", "w", encoding="utf-8") as file:
    file.write("First linenSecond linenThird linen")

The last n is optional. Include it if you want the file to end with a line terminator. In text mode, Python translates n to the platform’s default line ending. The Python tutorial notes that write() returns the number of characters written.

Write a list of lines

When each line is already a separate string, you can use writelines()—but it does not add newline characters or any other separators. Include the separator in each string:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
lines = ["First linen", "Second linen", "Third linen"]

with open("output.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)

The Python I/O reference says line separators are not added, so each supplied string usually needs one. If your strings do not already end in newlines, join them instead:

lines_without_newlines = ["First line", "Second line", "Third line"]

with open("output.txt", "w", encoding="utf-8") as file:
    file.write("n".join(lines_without_newlines) + "n")

Write values one line at a time

For values that need conversion or formatting, loop over them and write each formatted string with a newline. Text-mode write() expects a string, so convert numbers or other values before writing.

values = ["alpha", "beta", "gamma"]

with open("output.txt", "w", encoding="utf-8") as file:
    for value in values:
        file.write(f"{value}n")

Choose whether to replace or append

The mode passed to open() determines what happens to existing content:

  • "w" creates the file if needed and erases its existing contents when opened.
  • "a" creates the file if needed and adds new writes at the end.

For example, change the mode in the open() call to append:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("output.txt", "a", encoding="utf-8") as file:
    file.write("An additional linen")

Use a context manager and an explicit encoding

Opening the file with with ensures it is closed when the block exits, including if an exception occurs. Closing also allows buffered output to be handled reliably. The Python tutorial recommends specifying an encoding such as "utf-8" for ordinary text because the default encoding can depend on the platform.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Text files and binary files are different

These examples are for text. Text mode handles newline translation; if you are writing raw bytes such as JPEG or EXE data, use binary mode instead. Text encoding and newline handling are not a substitute for writing binary data.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.