May 2020
M T W T F S S
« Mar    
 123
45678910
11121314151617
18192021222324
25262728293031

Categories

WordPress Quotes

History is a relentless master. It has no present, only the past rushing into the future. To try to hold fast is to be swept aside.
John F. Kennedy
May 2020
M T W T F S S
« Mar    
 123
45678910
11121314151617
18192021222324
25262728293031

Short Cuts

2012 SERVER (64)
2016 windows (9)
AIX (13)
Amazon (40)
Ansibile (19)
Apache (135)
Asterisk (2)
cassandra (2)
Centos (211)
Centos RHEL 7 (270)
centos8 (3)
chef (3)
cloud (2)
cluster (3)
Coherence (1)
DB2 (5)
DISK (25)
DNS (9)
Docker (30)
Eassy (11)
ELKS (1)
EXCHANGE (3)
Fedora (6)
ftp (5)
GIT (3)
GOD (2)
Grub (1)
Hacking (10)
Hadoop (6)
health (2)
horoscope (23)
Hyper-V (10)
IIS (15)
IPTABLES (15)
JAVA (7)
JBOSS (32)
jenkins (1)
Kubernetes (7)
Ldap (5)
Linux (188)
Linux Commands (166)
Load balancer (5)
mariadb (14)
Mongodb (4)
MQ Server (24)
MYSQL (84)
Nagios (5)
NaturalOil (13)
Nginx (35)
Ngix (1)
openldap (1)
Openstack (6)
Oracle (35)
Perl (3)
Postfix (19)
Postgresql (1)
PowerShell (2)
Python (3)
qmail (36)
Redis (12)
RHCE (28)
SCALEIO (1)
Security on Centos (29)
SFTP (1)
Shell (64)
Solaris (58)
Sql Server 2012 (4)
squid (3)
SSH (10)
SSL (14)
Storage (1)
swap (3)
TIPS on Linux (28)
tomcat (62)
Ubuntu (1)
Uncategorized (30)
Veritas (2)
vfabric (1)
VMware (28)
Weblogic (38)
Websphere (71)
Windows (19)
Windows Software (2)
wordpress (1)
ZIMBRA (17)

WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.

Who's Online

0 visitors online now
0 guests, 0 bots, 0 members

Hit Counter provided by dental implants orange county

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>

  

  

  

Blue Captcha Image
Refresh

*

Protected by WP Anti Spam