Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Reading and Writing to text files in Python
Next article icon

Writing to file in Python

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail.

Creating a File

Creating a file is the first step before writing data to it. In Python, we can create a file using the following three modes:

  • Write (“w”) Mode: This mode creates a new file if it doesn’t exist. If the file already exists, it truncates the file (i.e., deletes the existing content) and starts fresh.
  • Append (“a”) Mode: This mode creates a new file if it doesn’t exist. If the file exists, it appends new content at the end without modifying the existing data.
  • Exclusive Creation (“x”) Mode: This mode creates a new file only if it doesn’t already exist. If the file already exists, it raises a FileExistsError.

Example:

Python
# Write mode: Creates a new file or truncates an existing file  with open("file.txt", "w") as f:     f.write("Created using write mode.")  f = open("file.txt","r") print(f.read())  # Append mode: Creates a new file or appends to an existing file  with open("file.txt", "a") as f:     f.write("Content appended to the file.")  f = open("file.txt","r") print(f.read())  # Exclusive creation mode: Creates a new file, raises error if file exists  try:     with open("file.txt", "x") as f:         f.write("Created using exclusive mode.") except FileExistsError:     print("Already exists.") 

Output
Created using write mode. Created using write mode.Content appended to the file. Already exists. 

Writing to an Existing File

If we want to modify or add new content to an already existing file, we can use two methodes:

write mode (“w”): This will overwrite any existing content,

writelines(): Allows us to write a list of string to the file in a single call.

Example:

Python
# Writing to an existing file (content will be overwritten) with open("file1.txt", "w") as f:     f.write("Written to the file.")      f = open("file1.txt","r") print(f.read())  # Writing multiple lines to an existing file using writelines() s = ["First line of text.\n", "Second line of text.\n", "Third line of text.\n"]  with open("file1.txt", "w") as f:     f.writelines(s)      f = open("file1.txt","r") print(f.read()) 

Output
Written to the file. First line of text. Second line of text. Third line of text.

Explanation:

  • open(“example.txt”, “w”): Opens the file example.txt in write mode. If the file exists, its content will be erased and replaced with the new data.
  • file.write(“Written to the file.”): Writes the new content into the file.
  • file.writelines(lines): This method takes a list of strings and writes them to the file. Unlike write() which writes a single string writelines() writes each element in the list one after the other. It does not automatically add newline characters between lines, so the \n needs to be included in the strings to ensure proper line breaks.

Writing to a Binary File

When dealing with non-text data (e.g., images, audio, or other binary data), Python allows you to write to a file in binary mode. Binary data is not encoded as text, and using binary write mode ("wb") ensures that the file content is handled as raw bytes.

Example:

Python
# Writing binary data to a file bin = b'\x00\x01\x02\x03\x04'  with open("file.bin", "wb") as f:     f.write(bin)  f = open("file.bin","r") print(f.read()) 

Output
 

Explanation:

  • bin= b’\x00\x01\x02\x03\x04′: The b before the string indicates that this is binary data. Each pair represents a byte value.
  • open(“file.bin”, “wb”): Opens the file file.bin in binary write mode. If the file doesn’t exist, Python will create it.
  • file.write(bin): Writes the binary data to the file as raw bytes.


Next Article
Reading and Writing to text files in Python

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • Writing CSV files in Python
    CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support. Ways to Write CSV Files in PythonBelow a
    11 min read
  • Working with csv files in Python
    Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
    10 min read
  • Working with zip files in Python
    This article explains how one can perform various operations on a zip file using a simple python program. What is a zip file? ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectl
    5 min read
  • Python - Write Bytes to File
    Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file c
    2 min read
  • Reading and Writing to text files in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
    8 min read
  • Read File As String in Python
    Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
    3 min read
  • Setting file offsets in Python
    Prerequisite: seek(), tell() Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer
    4 min read
  • Reading and Writing JSON to a File in Python
    The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
    3 min read
  • Reading and Writing CSV Files in Python
    CSV (Comma Separated Values) format is one of the most widely used formats for storing and exchanging structured data between different applications, including databases and spreadsheets. CSV files store tabular data, where each data field is separated by a delimiter, typically a comma. Python provi
    4 min read
  • Reading and Writing XML Files in Python
    Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format. In this article, methods have been described to read and write XM
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences