April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

Categories

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

Python file and DIRECTORY

import os
import os.path

PATH='./file.txt'

if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print "File exists and is readable"
else:
    print "Either file is missing or is not readable"


import os
fname = "foo.txt"
if os.path.isfile(fname):
    print "file does exist at this time"
else:
    print "no such file"
  1. Try opening the file:Opening the file will always verify the existence of the file. You can make a function just like so:
    def File_Existence(filepath):
        f = open(filepath)
        return True 

    If it’s False, it will stop execution with an unhanded IOError or OSError in later versions of python. To catch the exception, you have to use a try except clause. Of course, you can always use a try except statement like so (Thanks to hsandt for making me think):

    def File_Existence(filepath):
        try:
            f = open(filepath)
        except IOError, OSError: # Note OSError is for later versions of python
            return False
    
        return True
  2. Use os.path.exists(path):This will check the existence of what you specify. However, it checks for files and directories so beware about how you use it.
    import os.path
    >>> os.path.exists("this/is/a/directory")
    True
    >>> os.path.exists("this/is/a/file.txt")
    True
    >>> os.path.exists("not/a/directory")
    False
  3. Use os.access(path, mode):This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in os.F_OK, will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. (EAFP vs LBYP). If you’re not going to open the file afterwards, and only checking its existence, then you can use this.Anyways, here:
    >>> import os
    >>> os.access("/is/a/file.txt", os.F_OK)
    True
 


Directory 



import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

os provides you with a lot of these capabilities:

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in
 
 

Make directory on python 

import os

dirname = 'create/me'

try:
    os.makedirs(dirname)
except OSError:
    if os.path.exists(dirname):
        # We are nearly safe
        pass
    else:
        # There was an error on creation, so make sure we know about it
        raise
 

How To Check If A File Exists

If you find yourself doing any kind of disk-based I/O with Python, you’ll undoubtedly come across the need to verify that a file exists before continuing to read/write against it. There are multiple ways to do this but also some things you should watch for.

You may initially discover the os.path.exists() method, but keep in mind that this will yield True for both files and directories. This lack of specificity could easily introduce bugs and data loss if not expected.

#Returns true for directories, not just files
>>> print os.path.exists('/this/is/a/dir')
True

If you want to zero-in on just files, stick to os.path.isfile() method. Remember that something could happen to a file in the time between checking that it exists and actually preforming read/write operations against it. This approach will not lock the file in any way and therefore your code can become vulnerable to “time of check to time of use” (TOCTTOU) bugs.

#Returns true for directories, not just files
if os.path.isfile('my_settings.dat'):
    #...
    with open('my_settings.dat') as file:
       pass  #Potential for unhandled exception
True

Yes, that’s a real thing. Wikipedia has an article on TOCTTOU bugs, along with an example of how symlinks can be used by an attacker. I encourage you to read it.

Raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. Consider handling missing files with IOErrors, rather than if statements. In this situation, an IOError exception will be raised if the file exists but the user does not have read permissions.

try:
    with open('my_settings.dat') as file:
        pass
except IOError as e:
    print "Unable to open file" #Does not exist OR no read permissions

Check If a File Exists and Then Delete It in Python

 
#!/usr/bin/python
import os
 
## get input ##
filename=raw_input("Type file name to remove: ")
 
## delete only if file exists ##
if os.path.exists(filename):
    os.remove(filename)
else:
    print("Sorry, I can not remove %s file." % filename)

 

A Better Option To Delete A File In Python

The following code gives an error information when it can not delete the given file name:

 
#!/usr/bin/python
import os
 
## get input ##
filename=raw_input("Type file name to remove: ")
 
## check if a file exists on disk ##
## if exists, delete it else show message on screen ##
if os.path.exists(filename):
	try:
		os.remove(filename)
	except OSError, e:
		print ("Error: %s - %s." % (e.filename,e.strerror))
else:
	print("Sorry, I can not find %s file." % filename)

Sample outputs:

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>