Python check if file is in use

How to check if file exists in Python?

In this short tutorial, we look at how to check if a file exists in Python We look at why is it important to check the existence of file before performing any operations on them, and the various methods used to confirm if a file is present in Python.

Table of Contents — Python check if file exists

  1. Why do we need to check if a file exists?
  2. Methods to check if file exists
    • Using OS module
      • os.path.isfile() method
      • os.path.exists() method
      • os.path.isdir() method
    • Using pathlib module
      • pathlib.path.exists() method
      • pathlib.is_file() method
    • Using Glob module
    • Using sub-process (only for Unix)
    • Exception handling method
  3. Closing thoughts

Why do we need to check if a file exists?

We can perform various operations in Python. After creating a file, we can perform operations on the files to read, update, copy or even delete them. If we code to perform any of these operations on a file, and the file doesn’t exist, then we will need to overwrite the code after making sure that the file exists at the defined path.

Читайте также:  Javascript current time formatted

Thus, to perform functions on a file and prevent our program from crashing, we first need to ensure that the file exists.

There are various methods to do this. We can use Python libraries or can use other methods for the same. Let us look at them one by one.

Methods to check if file exists

Using os module

Os is a built-in Python module that contains functions for interacting with the operating system. Using os allows us to access the operating system functions. os.path is a sub-module of os in Python. This is used to manipulate common path name.

The os.path has two methods- isfile() and exists() that outputs ‘True’ or ‘False’ depending on whether a file exists or not.

os.path.isfile() method-

The syntax is as follows:

Parameters- Path: represents the path to the file
Return type: ‘True’ or ‘False’ depending on whether a file exists or not Example-

import os path= 'C:\Users\filename.txt' isFile = os.path.isfile(path) print (isFile) 

If the file named ‘filename.txt’ is present, the output will be ‘True’, else ‘False’.

os.path.exists() method-

The syntax is as follows:

Parameters- Path: represents the path to the file
Return type: ‘True’ or ‘False’ depending on whether a file exists or not Example-

import os path= 'C:\Users\filename.txt' isExist = os.path.exists(path) print(isExist) 

If the file named ‘filename.txt’ is present, the output will be ‘True’, else ‘False’.

os.path.isdir() method-

The syntax is as follows:

Parameters- Path: represents the path to the file
Return type: ‘True’ or ‘False’ depending on whether a file exists or not Example-

import os.path path= 'C:\Users\filename.txt' isDir = os.path.exists(path) print(isDir) 

Here, as our file is not a directory, we will get the output as «False».

Note that before using the os.path.isfile() method, os.path.exists() method, or the os.path.isdir() method, os.path module should be imported.

Using pathlib module

Pathlib is a python built-in object oriented interface that provides an object API for working with files and directories. Like the os module, there are two ways to find if the exists using pathlib module.

pathlib.path.exists() method

import pathlib file = pathlib.Path("C:/Users/filename.txt") if file.exists(): print ("File exist") else: print ("File does not exist") 

pathlib.is_file() Method

import pathlib file = pathlib.Path("C:/Users/filename.txt") if file.is_file(): print ("File exist") else: print ("File does not exist") 

The difference between os module and pathlib module is that the os.path module needs function nesting, whereas the pathlib modules Path class allows us to chain methods and attributes on Path objects to get an equivalent path representation. The pathlib module has similar functions like the os module for finding if the file exists.

Using Glob module

The glob module is used to search for files where the filename matches a certain pattern by using wildcard characters. This, too, returns «True» or «False» values for indicating if the file exists.
Example-

import glob if glob.glob(r"C:\Users\filename.txt"): print ("File exist") else: print("File does not exist") 

Using sub-process (only for Unix)

If you are using Unix based machine, this method can be applicable for you. There are test commands in the sub-process module that can be used to find if the file or directory is present.
The first step is to make sure that the path to the file/directory exists, using «test -e». If the path exists, we then check for the existence of the file/directory using «test -f» or «test -d» respectively.

from subprocess import run run (['test', '-e', 'filename.txt']).returncode == 0 
run(['test', '-f', 'filename.txt']).returncode == 0 

Exception handling method

In the try and except statements, we have code written under «try» and the «except» statement tests the code for error under «try» . If any error is present, the «except» block are run. Hence, we check if the file exists or not by opening the file using the «try» statement. If the file is not present, IOError Exception occurs, for which we can print the output to indicate that the file does not exists.
The first step is to make sure that the path to the file/directory exists, using «test -e». If the path exists, we then check for the existence of the file/directory using «test -f» or «test -d» respectively.
Example-

try: file = open('filename.txt') print("File exists") file.close() except IOError: print("File does not exists") 

One more way to use the try and except method is shown in the example below. Here, if we try to open a file that does not exist, Python will give the FileNotFoundError.

file = open('filename.txt') try: file.close() print("File exists") except FileNotFoundError: print("File does not exists") 

In both the cases, the output will be «File exists» or «File does not exists» depending upon whether the file is present or not.

Closing thoughts

Before performing any operations on the files, it is a good practice to check if the file exists or not. This will avoid overwriting the code in case file is not present. Here, we have seen various methods to check if the file exists or not.

The first method among those is commonly used and can be recommended for beginners. When the libraries are not to be used, we can go with the try and except method, or the exception handling method.

However, please feel free to explore and understand how the multiline method works.

Источник

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
  1. 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.

Источник

Оцените статью