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:
Check If A File is Valid Image with Python
Next article icon

Check If A File is Writable in Python

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When it comes to Python programming it is essential to work with files. One important aspect is making sure that a file can be written before you try to make any changes. In this article, we will see how we can check if a file is writable in Python.

Check If a File Is Writable in Python

Below are some of the ways by which we can check if a file is writable in Python:

  • Using os.access() Function
  • Verifying Writability
  • Using the file object's writable() method

Using the os.access() Function

This method is more useful to check if the given file is writable, and whether the matter file exists or not. It uses the os.access() function that inquires about the permissions of the specified file, from the operating system.

Python3
import os  # Replace with the actual file path file_path = "C:/Users/Pankaj Kumar Bind/Downloads/Test.txt"  try:     # Check if the file is writable using os.access()     if os.access(file_path, os.W_OK):         print(f"File '{file_path}' is writable.")      else:         print(f"File '{file_path}' is not writable.")  except FileNotFoundError:     print(f"File '{file_path}' does not exist.") except PermissionError:     print(f"You don't have permission to access or write to '{file_path}'.") 

Output:

example1

Verifying Writability

This approach follows Python conventions and this is more succinct especially when working with existing files. It tries to open the file in mode ("w") and verifies if a PermissionError exception occurs.

Python3
import os  # Replace with the actual file path filepath = "C:/Users/Pankaj Kumar Bind/Desktop/test.txt"  def isFileWritable(filepath):     """Checks if a file is writable by attempting to open it in write mode.      Args:         filepath (str): The path to the file.      Returns:         bool: True if the file is writable, False otherwise.     """      try:         with open(filepath, "w") as f:             # Write something to verify writability             f.write("Test")             return True     except PermissionError:         return False  if isFileWritable(filepath):     print(f"{filepath} is writable.") else:     print(f"{filepath} is not writable.") 

Output:

example2

Using writable() Method

This method is the most efficient approach if you've already opened the file in write mode ("w"). To determine if a file is writable it simply invokes the writable() method, on the file object.

Python3
def isFileWritable(file_object):     """Checks if an already opened file is writable.      Args:         file_object: The opened file object.      Returns:         bool: True if the file is writable, False otherwise.     """      return file_object.writable()  # Provide the file path here filepath = "example3.py"   # Open the file in write mode with open(filepath, "w") as f:     # Check if the opened file is writable     if isFileWritable(f):         print(f"The file {filepath} is writable.")     else:         print(f"The file {filepath} is not writable.") 

Output:

example3


Next Article
Check If A File is Valid Image with Python
author
pankajbind
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Check If File is Readable in Python
    We are given a file and we have to check whether the file is readable in Python or not. In this article, we will see how we can check if a file is readable or not by using different approaches in Python. How to Check if a File is Readable in PythonBelow, are the methods of How to Check If a File Is
    3 min read
  • Check If A File is Valid Image with Python
    When working with images in Python, it's crucial to ensure the integrity and validity of the files being processed. Invalid or corrupted image files can lead to unexpected errors and disruptions in your applications. In this article, we will explore different methods to check if a file is a valid im
    3 min read
  • Check If a Text File Empty in Python
    Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python. Check if
    4 min read
  • Check if a File Exists in Python
    When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error. Using pathlib.Path.exists (Recommended Method)Starting with Python 3.4
    3 min read
  • How to Check if a Variable is a String - Python
    The goal is to check if a variable is a string in Python to ensure it can be handled as text. Since Python variables can store different types of data such as numbers, lists or text, it’s important to confirm the type before performing operations meant only for strings. For example, if a variable co
    3 min read
  • Create a File Path with Variables in Python
    The task is to create a file path using variables in Python. Different methods we can use are string concatenation and os.path.join(), both of which allow us to build file paths dynamically and ensure compatibility across different platforms. For example, if you have a folder named Documents and a f
    3 min read
  • Check end of file in Python
    In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string. [GFGTABS] Python f = open("file.txt",
    2 min read
  • Close a File in Python
    In Python, a file object (often denoted as fp) is a representation of an open file. When working with files, it is essential to close the file properly to release system resources and ensure data integrity. Closing a file is crucial to avoid potential issues like data corruption and resource leaks.
    2 min read
  • Print the Content of a Txt File in Python
    Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
    3 min read
  • Check a File is Opened or Closed in Python
    In computer programming, working with files is something we often do. Python, a programming language, gives us useful tools to handle files. One important thing to know when dealing with files is whether a file is currently open or closed. This is crucial to avoid problems and make sure the data sta
    3 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