Python Writelines – File writelines() Method

Python writelines() method adds a string to the file one at a time. The sequence can be any object that can be used over and over to make strings, usually a list of strings. There is no value in the return.

a“: The texts will be inserted at the current file stream position, default at the end of the file.

w“: The file will be emptied before the texts will be inserted at the current file stream position, default 0.

Also read: How To Make Dino Game In Python Using PyGame

Syntax

The following code given below is the syntax for Python writelines() method.

file.writelines(list)

Parameter Values

  • list -The list of texts or byte objects that will be inserted.

Return Value

This method does not return any value.

Example

The following example given below shows the usage of writelines() in Python method.

f = open("test.txt", "a")
f.writelines(["\nI Miss You!", "\nSee You Soon!."])
f.close()

#open and read the file after the appending:
f = open("test.txt", "r")
print(f.read())

When you execute the program, this will be the output.

I Miss You!
See You Soon!.

Difference Between write() and writelines() Function In Python

There are a lot of ways to read and write files in Python. Files that are open can be read and written to (files opened and linked via a file object).

In this section, we’ll talk about the write functions that let us change our data by writing to files.

Write() Function

The write() function will write the content of the file without adding any extra characters.

Syntax

# Writes string content referenced by file object.
file_name.write(content)

Using the syntax, the string that is passed to the write() function is written into the opened file. There might be numbers, special characters, or symbols in the string.

When writing data to a file, we must know that the write function does not add a newline character (n) to the end of the string. The function write() gives the value None.

Example

file = open("test.txt", "w")

for i in range(3):
    name = input("Enter the name of the employee: ")
    file.write(name)
    file.write("\n")

file.close()

print("Data is written into the file.")

Output:

Enter the name of the employee: Angel Jude Suarez
Enter the name of the employee: Glenn Azuelo
Enter the name of the employee: Paul Blauro
Data is written into the file.

Writelines() Function

The writelines() function writes the content of a list to a file.

Syntax

# write all the strings present in the list "list_of_lines" 
# referenced by file object.
file_name.writelines(list_of_lines)

According to the syntax, the list of strings that are given to the writelines() function is written into the file that has been opened.

The writelines() function is like the write() function in that it does not add a newline character (\n) to the end of the string.

Example

file1 = open("test.txt", "w")
lst = []
for i in range(3):
    name = input("Enter the name of the employee: ")
    lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Data is written into the file.")

Output:

Enter the name of the employee: Angel Jude Suarez
Enter the name of the employee: Glenn Azuelo
Enter the name of the employee: Paul Blauro
Data is written into the file.

Frequently Asked Questions

What Does Writeline Do Python?

Python writelines() method adds a string to the file one at a time. The sequence can be any object that can be used over and over to make strings, usually a list of strings. There is no value in the return.
“a”: The texts will be inserted at the current file stream position, default at the end of the file.
“w”: The file will be emptied before the texts will be inserted at the current file stream position, default 0.

What Is The Difference Between write() and writelines() Function In Python?

The only difference between write() and writelines() is that write() writes a string to a file that has already been opened, while writelines() writes a list of strings to a file that has already been opened.

What Is Correct Syntax Of writelines() Method?

The correct system of writelines() method is: fileObject. writelines( sequence ).

How Do You Write Multiple Lines In A Text File In Python?

Use file.writelines(lines) with lines as a list of strings. If you want each string to be written on a separate line, add the “\n” newline character to the end of each string. If you don’t do this, the strings will be written on a single line.

Does Python Writelines Immediately Flush?

The Python file method flush() works like stdio’s fflush in that it flushes the internal buffer. On some file-like objects, this may do nothing.
When files are closed in Python, they are automatically flushed.

Conclusion

We have completely discussed the tutorial about Python Writelines and the differences between write functions, In this tutorial, we learn with the help of examples. I hope this simple Python Tutorial will help you a lot.

Thank You!

Inquiries

By the way, If you have any questions or suggestions about this simple python tutorial. Please feel free to comment below.

Related Python Tutorials

Common use cases for Python Writelines – File writelines() Method

  • Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
  • Web development. Django and FastAPI power modern web backends and APIs.
  • Automation and scripting. System administration, file processing, web scraping, and cron jobs.
  • Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
  • Educational tools. Python’s readability makes it the go-to teaching language.

Working code example

from typing import Optional

def process_data(items: list[dict]) -> Optional[dict]:
    """Process a list of items and return summary stats."""
    if not items:
        return None
    return {
        "count": len(items),
        "total": sum(item.get("value", 0) for item in items),
        "avg": sum(item.get("value", 0) for item in items) / len(items),
    }

# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary)  # {'count': 3, 'total': 60, 'avg': 20.0}

Best practices

  • Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
  • Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
  • Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
  • Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
  • Use ruff or pylint. Static analysis catches many bugs before code runs.

Common pitfalls

  • Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
  • Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
  • Missing self on methods. Class methods need self as first parameter.
  • Late binding closures. Loops that create lambdas can capture variables late.

Frequently Asked Questions

What Python version does this tutorial target?
This tutorial targets Python 3.10 or higher. Most examples work on 3.8+, but newer features (match statements, pipe union types, structural pattern matching) need 3.10+. For deep learning content, Python 3.11 is recommended for best performance.
How do I install Python for this tutorial?
Download Python 3.11 or higher from python.org. On Windows, tick ‘Add to PATH’ during install. On Mac use Homebrew (brew install python). On Linux use your package manager or pyenv for version management.
Do I need pip and virtual environments?
Yes. pip comes with Python. For any project beyond a single script, create a virtual environment: python -m venv venv, then activate and pip install dependencies. This keeps project libraries isolated.
Can I use this in a Jupyter notebook or Google Colab?
Most examples run in both. Colab is great for ML tutorials since it provides free GPU access. Jupyter is better for local iterative development. Just paste the code into a cell and run.
Where can I find more Python practice projects?
Browse itsourcecode.com Python Projects for 250+ free capstone-ready systems (sentiment analysis, image classification, chatbots, LangChain apps). Each includes full source code, dataset links, and installation instructions.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment