- Python How to Check if File can be Read or Written
- 1. Introduction
- 2. Check if File can be Read
- 2.1. Using access()
- 3. Checking if file can be written
- 3.1. Attempt to Write File
- 3.2. Using access() for checking
- 3.3. Checking Results
- Conclusion
- How to check a file is opened or closed in Python
- Create a file for checking:
- Example-1: Check the file is opened or not by using IOError
- Output:
- Example-2: Check the file is closed or not by using the closed property.
- Output:
- Example-3: Check the file is opened or not by using OSError
- Output:
- Conclusion:
- About the author
- Fahmida Yesmin
Python How to Check if File can be Read or Written
Collection of Checks for Readable and Writable Files.
“Education is the most powerful weapon which you can use to change the world.” ― Nelson Mandela
1. Introduction
It can be a bit cumbersome at times to check for read or write permission on a file. The check might succeed but the actual operation could fail. Also, quite a few edge cases need to be covered to get a reasonable answer from such a check. In this article, we cover some issues with regards to checking read and write permission on a file.
2. Check if File can be Read
A file can be read if it exists and has read permission for the user. Attempting to open the file is the simplest way you can find out if a file can be read. You get an IOError exception if the file cannot be read and you can check errno in the exception for details.
- If errno is errno.ENOENT, the file does not exist.
- If errno is errno.EACCES, the user does not have permission to read the file.
try: with open(argv[1]) as f: s = f.read() print 'read', len(s), 'bytes.' except IOError as x: if x.errno == errno.ENOENT: print argv[1], '- does not exist' elif x.errno == errno.EACCES: print argv[1], '- cannot be read' else: print argv[1], '- some other error'
2.1. Using access()
Sometimes, you don’t care about the reason that open() fails. You just want to know if it succeeds. In such cases, os.access() is an option.
print os.access('joe.txt', os.R_OK) # prints False
print os.access('joe.txt', os.R_OK) # prints False
print os.access('joe.txt', os.R_OK) # prints False
- By the time you check access() and attempt to actually open the file, the situation may have changed. A readable file might be gone or have its permission changed.
3. Checking if file can be written
Check for file-write is a little bit different from checking readability. If the file does not exist, we need to check the parent directory for write permission.
3.1. Attempt to Write File
Sometimes, the easiest way is to just attempt to write the file. And catch the exception if any is raised.
try: with open(argv[1], 'w') as f: # file opened for writing. write to it here print 'ok' pass except IOError as x: print 'error ', x.errno, ',', x.strerror if x.errno == errno.EACCES: print argv[1], 'no perms' elif x.errno == errno.EISDIR: print argv[1], 'is directory'
As above, the disadvantage of this method is the expense of raising and checking an exception.
3.2. Using access() for checking
When using access() to check permissions, you need not actually open the file. You can apply various conditions to verify writability. In the following procedure, we describe how to go about checking whether a particular file is writable.
- Check if the path exists. Different conditions need to be checked depending on whether it exists or not.
if os.path.exists(fnm): # path exists if os.path.isfile(fnm): # is it a file or a dir? .
if os.path.exists(fnm): # path exists if os.path.isfile(fnm): # is it a file or a dir? # also works when file is a link and the target is writable return os.access(fnm, os.W_OK) .
if os.path.exists(fnm): # path exists if os.path.isfile(fnm): # is it a file or a dir? # also works when file is a link and the target is writable return os.access(fnm, os.W_OK) else: return False # path is a dir, so cannot write as a file .
Here is the complete program.
import os.path def check_file_writable(fnm): if os.path.exists(fnm): # path exists if os.path.isfile(fnm): # is it a file or a dir? # also works when file is a link and the target is writable return os.access(fnm, os.W_OK) else: return False # path is a dir, so cannot write as a file # target does not exist, check perms on parent dir pdir = os.path.dirname(fnm) if not pdir: pdir = '.' # target is creatable if parent dir is writable return os.access(pdir, os.W_OK) if __name__ == '__main__': from sys import argv print argv[1], '=>', check_file_writable(argv[1])
3.3. Checking Results
Let us now check to see how it works.
- First, remove the checked file and check.
rm joe python check.py joe # prints joe => True
touch joe ls -l joe # prints -rw-rw-r-- 1 xxxxxxx xxxxxxx 0 Feb 10 12:01 joe
python check.py joe # prints joe => True
chmod -w joe python check.py joe # prints joe => False
rm joe; chmod -w . python check.py joe # prints joe => False
chmod +w . mkdir joe python check.py joe # prints joe => False
rmdir joe ln -s not-exists joe python check.py joe # prints joe => True
touch not-exists chmod -w not-exists python check.py joe # prints joe => False
Conclusion
In this article, we have presented a review of methods to check for readability and writability of a file. Opening the file is the surest way to check, but has the cost of raising and catching an exception. Using access() will work, but might be subject to race conditions. Use the knowledge presented here to adjust to your needs.
How to check a file is opened or closed in Python
The file is used to store data permanently. Working with a file is a very common task of any programming language. Many built-in functions exist in Python to create, open, read, write and close the file. Two types of files can be created to store data. These are text files and binary files. Any file is required to open before reading or write. The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated. Another way to check a file is opened or closed is to check the values of the closed property of the file handler object. Using rename() function is another way to check the file is opened or closed. Different ways to check any file is opened or closed in Python have been shown in this tutorial.
Create a file for checking:
You can use any existing file or create a new file to test the example code shown in this tutorial. A new text file named clients.txt has been created with the following content to use later in the next part of the tutorial.
ID Name Email
01 Jony Liver jony@gmail.com
02 Manik Hossain manik@gmail.com
03 Neha Akter neha@gmail.com
04 Janatul Ferdous jannat@gmail.com
05 Helal Uddin helal@gmail.com
Example-1: Check the file is opened or not by using IOError
IOError generates when the open() function is called to open a file that has been opened before. Create a python file with the following script to check a file is opened or not by using try-except block. Here, any existing filename will be taken as input and opened for reading. Next, the open() function is called again to open the same file that will raise an IOError and print the error message.
# Take the filename to check
filename = input ( «Enter any existing filename: \n » )
# Open the file for the first time using open() function
fileHandler = open ( filename , «r» )
# Try to open the file same file again
try :
with open ( «filename» , «r» ) as file :
# Print the success message
print ( «File has opened for reading.» )
# Raise error if the file is opened before
except IOError :
print ( «File has opened already.» )
Output:
The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the error message, “File has opened already,” has printed for the IOError exception.
Example-2: Check the file is closed or not by using the closed property.
The value of the closed property will be true if any file is closed. Create a python file with the following script to check a file is closed or not that exists in the current location. The previous example script will generate an error if the filename taken from the user does not exist in the current location. This problem has solved in this example. The os module is used here to check the existence of the filename that will be taken from the user. The check_closed() function has defined to check the file is closed or not that will be called if the file exists.
# Import os module to check the existence of the file
import os
# Drfine function check the file is closed or not
def check_closed ( ) :
if fileHandler. closed == False :
# Print the success message
print ( «File has opened for reading.» )
else :
# Print the error message
print ( «File has closed.» )
# Take the filename to check
filename = input ( «Enter any existing filename: \n » )
# Check the file exist or not
if os . path . exists ( filename ) :
# Open the file for reading
fileHandler = open ( filename , «r» )
# Call the function
check_closed ( )
else :
# Print message if the file does not exist
print ( «File does not exist.» )
Output:
The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the success message, “File has opened for reading,” has printed because the value of the closed property returned False.
Example-3: Check the file is opened or not by using OSError
The OSError generates when the rename() function is called more than one time for a file that is opened already. Create a python file with the following script to check a file is opened or closed by using OSError. The os module has been used in the script to check the file’s existence and rename the file. When the rename() function is called for the second time, OSError will be generated, and the custom error message will be printed.
# Import os module to check the existence of the file
import os
# Set the existing filename
filename = ‘clients.txt’
# Set the new filename
newname = ‘customers.txt’
# Check the file exist or not
if os . path . exists ( filename ) :
try :
# Call the rename function for the first time
os . rename ( filename , newname )
# Call the rename function for the second time
os . rename ( filename , newname )
# Raise error if the file has opened
except OSError :
print ( «File is still opened.» )
else :
# Print message if the file does not exist
print ( «File does not exist.» )
Output:
The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the error message, “File is still opened,” has printed because the OSError exception has generated when the second rename() function has been executed.
Conclusion:
When we need to work with the same file multiple times in a script, it is essential to know whether the file is opened or closed. It is better to call the close() function to close the file after completing the file operation. The error occurs when a file is opened for the second time in the same script without closing it. Different solutions to this problem have been shown in this tutorial by using simple examples to help the python users.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.