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
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.
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.
The correct system of writelines() method is: fileObject. writelines( sequence ).
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.
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
- Python Import Class From Another File With Examples
- Python Private Method With Examples
- Python Ceiling Method With Examples
- Python Capitalization Method With Examples
- Python Endswith Method With Examples
- Python Uppercase Method With Examples
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.
