onlyforbopi
7/16/2018 - 6:14 AM

Python.OS.Paths.Pathnames

Python.OS.Paths.Pathnames #python #Python #OS #filepath #filename #file #pathname #osmodule

  1. Convert input path to raw string
  2. Absolute path to file
  3. Basename path to file
  4. Dirname path to file
  5. Check if file exists
  6. Get last access time
  7. Get last modified time
  8. Get creation time
  9. Get file size
  10. Check if path is absolute
  11. Normalize a path
  12. Join two paths intelligently
  13. Split dirname/basename -> List
  14. Split Drive / Rest of path -> List
  15. Split file path / suffix -> List
  16. Split UNC path from full path
  17. Traverse a directory and all subdirs (os.walk)
# Split dirname / basename -> List
print(os.path.split(a))

# Split Drive / Rest -> List
print(os.path.splitdrive(a))

# Split file path / suffix -> List
print(os.path.splitext(a))

Yes. Use os.path.splitext(see Python 2.X documentation or Python 3.X documentation):

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

# Split UNC path from full path
print(os.path.splitunc(a))
# Join two paths intelligently
b = os.path.join("C:\\Users\\p.doulgeridis\\Desktop\\", "\\Python.Path.Manipulation.py") 
print("a is:" + str(a))
print("b is: " + str(b))
# Normalize path (Join \\.\\ etc)
a = os.path.normpath("C:\\Users\\p.doulgeridis\\Desktop\\.\\Python.Path.Manipulation.py")
# Check if path is absolute
print(os.path.isabs(sys.argv[0]))
###################################################
# Using os.path.walk

# OS.PATH.WALK
# Traverse a directory tree
# Iterate over all subdirs, and files
# rootDir = '.'
# for dirname, subdirList, fileList in os.walk(rootDir):
    # #print(dirname, subdirList, fileList)
    # print('Found directory: %s' % dirname)
    # for fname in fileList:
        # print('\t%s' % fname)

# iterate over all subdirs and files, starting from top
rootDir = '.'
for dirname, subdirList, fileList in os.walk(rootDir, topdown=True):
    #print(dirname, subdirList, fileList)
    print('Found directory: %s' % dirname)
    for fname in subdirList:
        print('\t%s' % fname)


###################################################


# iterate over all subdirs and files, starting from bottom
rootDir = '.'
for dirname, subdirList, fileList in os.walk(rootDir, topdown=False ):
    #print(dirname, subdirList, fileList)
    print('Found directory: %s' % dirname)
    for fname in subdirList:
        print('\t%s' % fname)
    

# \\\\\\\\\\\\\\\\
path = "c:\\python25"

i = 0
for (path, dirs, files) in os.walk(path):
    print path
    print dirs
    print files
    print "----"
    i += 1
    if i >= 4:
        break
    
#######################################################
# Get last creation date





#######################################################
# Function form 
def creationtimeHR(file_in, time_format):
    import os
    from datetime import datetime
    
    time_in = os.path.getctime(file_in)
    time_ot = datetime.fromtimestamp(time_in).strftime(time_format)
    return time_ot
 


print(creationtimeHR(sys.argv[0], '%Y-%m-%d %H:%M:%S'))
print(creationtimeHR(sys.argv[0], '%Y%m%d%H%M%S')) 
print(creationtimeHR(sys.argv[0], '%Y-%m-%d')) 
print(creationtimeHR(sys.argv[0], '%H%M%S')) 






#########################################################
# Get last modified time
print(os.path.getmtime(sys.argv[0]))

#########################################################
# Function form - Human Readable

def lastmodifytimeHR(file_in, time_format):
    import os
    from datetime import datetime
    
    time_in = os.path.getmtime(file_in)
    time_ot = datetime.fromtimestamp(time_in).strftime(time_format)
    return time_ot
    
    
print(lastmodifytimeHR(sys.argv[0], '%Y-%m-%d %H:%M:%S'))
print(lastmodifytimeHR(sys.argv[0], '%Y%m%d%H%M%S'))
print(lastmodifytimeHR(sys.argv[0], '%Y%m%d'))
print(lastmodifytimeHR(sys.argv[0], '%H:%M:%S'))
###########################################
# Get last access time 
print(os.path.getatime(sys.argv[0]))

##########################################
# Function form - Human Readable

def lastaccesstimeHR(file_in, time_format):
    '''
    Names: lastaccesstimeHR
    Functions: lastaccesstimeHR(file_in, time_format)
    Input:     * <file_in> or <sys.argv[0]>
               * time_format (look at examples)
    Output: Last access time, Human Readable
    Usage: print(lastaccesstimeHR(sys.argv[0], '%Y-%m-%d %H:%M:%S'))
    Notes: Using datetime module to convert to human readable date string.
    '''
    import os
    from datetime import datetime
    
    time_in = os.path.getatime(file_in)
    time_ot = datetime.fromtimestamp(time_in).strftime(time_format)
    return time_ot
    
    
print(lastaccesstimeHR(sys.argv[0], '%Y-%m-%d %H:%M:%S'))
print(lastaccesstimeHR(sys.argv[0], '%Y%m%d'))
print(lastaccesstimeHR(sys.argv[0], '%Y%m%d%H%M%S'))
print(lastaccesstimeHR(sys.argv[0], '%H:%M:%S'))

# to be able to calculate between different dates, we need to use the numerical 
# representation, use datetime module.
# Check if file exists
print(os.path.exists(sys.argv[0]))

# Check if a file is a file
print(os.path.isfile(sys.argv[0]))

# Check if a file is dir
print(os.path.isdir(sys.argv[0]))
###############################################
# To use dirname, we have to feed it abspath.


# dirname of script
print(os.path.dirname(os.path.abspath(sys.argv[0])))

# dirname of a file
print(os.path.dirname(os.path.abspath(file_in)))

def dirnameoffile(file_in):
  '''
  Notes: for dirname of script file_in = sys.argv[0]
  Notes: We have to use abspath to get dirname.
  '''
  return os.path.dirname(os.path.abspath(file_in))
  
  
  
#################################################
# dirname

def dirnameslash(file_in):

    import os
    return (str((os.path.dirname(os.path.abspath(file_in)))) + "\\")
    
    
print(dirnameslash(sys.argv[0]))


import os
import sys

file_in = sys.argv[1]

# absolute path of script
print(os.path.abspath(sys.argv[0]))

# absolute path of file in
print(os.path.abspath(file_in))


def abspathoffile(file_in):
  '''
  Note: for abs path of script file_in = sys.argv[1]
  '''
  return os.path.abspath(file_in)
import os
import sys

file_in = sys.argv[1]


# basename of script
print(os.path.basename(sys.argv[0]))

# basename of file
print(os.path.basename(file_in))


def basenameoffile(file_in):
  '''
  Notes: for basename path of script file_in = sys.argv[1]
  '''
  return os.path.basename(sys.argv[0])
  
# Convert input paths to Raw strings
    #path = r'%s' % variable
    in_file_conv = r'%s' % file_in
    ot_file_conv = r'%s' %file_ot