Best Python code snippet using autotest_python
fileops.py
Source:fileops.py  
1# v.0.12.42import os, re, sys3try:4    from kodi_six import xbmcvfs5    isXBMC = True6except ImportError:7    isXBMC= False8if isXBMC:9    _mkdirs  = xbmcvfs.mkdirs10    _rmdir   = xbmcvfs.rmdir11    _exists  = xbmcvfs.exists12    _delete  = xbmcvfs.delete13    _copy    = xbmcvfs.copy14    _open    = xbmcvfs.File15    _rename  = xbmcvfs.rename16else:17    import shutil18    _mkdirs  = os.makedirs19    _rmdir   = os.rmdir20    _exists  = os.path.exists21    _delete  = os.remove22    _copy    = shutil.copyfile23    _open    = open24    _rename  = os.rename25def checkPath( thepath, createdir=True ):26    log_lines = []27    log_lines.append( 'checking for %s' % thepath )28    if not _exists( thepath ):29        if createdir:30            log_lines.append( '%s does not exist, creating it' % thepath )31            _mkdirs( thepath )32        else:33            log_lines.append( '%s does not exist' % thepath )34        return False, log_lines35    else:36        log_lines.append( '%s exists' % thepath )37        return True, log_lines38def copyFile( thesource, thedest ):39    log_lines = []40    if _exists( thesource ):41        log_lines.append( 'copying file %s to %s' % (thesource, thedest) )42        try:43            _copy( thesource, thedest )44        except IOError:45            log_lines.append( 'unable to copy %s to %s' % (thesource, thedest) )46            return False, log_lines47        except Exception as e:48            log_lines.append( 'unknown error while attempting to copy %s to %s' % (thesource, thedest) )49            log_lines.append( e )50            return False, log_lines51        return True, log_lines52    else:53        log_lines.append( '%s does not exist' % thesource )54        return False, log_lines55def deleteFile( thesource ):56    return deleteFolder( thesource, thetype='file')57def deleteFolder( thesource, thetype='folder' ):58    log_lines = []59    if _exists( thesource ):60        if thetype == 'folder':61            #in Mac OSX the .DS_Store file, if present, will block a folder from being deleted, so delete the file62            try:63                _delete( os.path.join( thesource, '.DS_Store' ) )64            except IOError:65                log_lines.append( 'unable to delete .DS_Store file' )66            except Exception as e:67                log_lines.append( 'unknown error while attempting to delete .DS_Store file' )68                log_lines.append( e )69            _action = _rmdir70        else:71            _action = _delete72        log_lines.append( 'deleting %s %s' % (thetype, thesource) )73        try:74            if isXBMC:75                if not _action( thesource ):76                    raise IOError( 'unable to delete item' )77            else:78                _action( thesource )79        except IOError:80            log_lines.append( 'unable to delete %s' % thesource )81            return False, log_lines82        except Exception as e:83            log_lines.append( 'unknown error while attempting to delete %s' % thesource )84            log_lines.append( e )85            return False, log_lines86        return True, log_lines87    else:88        log_lines.append( '%s does not exist' % thesource )89        return False, log_lines90def listDirectory( thesource, thefilter='all' ):91    log_lines = []92    log_lines.append( 'getting contents of folder %s' % thesource )93    if isXBMC:94        try:95            dirs, files = xbmcvfs.listdir( thesource )96        except OSError:97            log_lines.append( 'OSError getting directory list' )98            return [], log_lines99        except Exception as e:100            log_lines.append( 'unexpected error getting directory list' )101            log_lines.append( e )102            return [], log_lines103        if thefilter == 'files':104            log_lines.append( 'returning files from %s' % thesource )105            log_lines.append( files )106            return files, log_lines107        elif thefilter =='folders':108            log_lines.append( 'returning folders from %s' % thesource )109            log_lines.append( dirs )110            return dirs, log_lines111        else:112            log_lines.append( 'returning files and folders from %s' % thesource )113            log_lines.append( files + dirs )114            return files + dirs, log_lines115    else:116        try:117            contents = os.listdir( thesource )118        except OSError:119            log_lines.append( 'OSError getting directory list' )120            return [], log_lines121        except Exception as e:122            log_lines.append( 'unexpected error getting directory list' )123            log_lines.append( e )124            return [], log_lines125        log_lines.append( 'returning files and folders from %s' % thesource )126        return contents, log_lines127def moveFile( thesource, thedest ):128    log_lines = []129    cp_loglines = []130    dl_loglines = []131    success = False132    if _exists( thesource ):133        cp_success, cp_loglines = copyFile( thesource, thedest )134        if cp_success:135            dl_success, dl_loglines = deleteFile( thesource )136            if dl_success:137                success = True138    else:139        log_lines.append( '%s does not exist' % thesource)140        success = False141    return success, log_lines + cp_loglines + dl_loglines142def _atoi( text ):143    return int(text) if text.isdigit() else text144def naturalKeys( thelist ):145    # from http://nedbatchelder.com/blog/200712/human_sorting.html146    return [ _atoi( c ) for c in re.split( r'(\d+)', thelist ) ]147def osPathFromString( spath, sep='/' ):148    pathlist = spath.split( sep )149    if spath.startswith( sep ):150        pathlist.insert( 0, os.sep )151        pathlist[2] = pathlist[2] + os.sep152    return os.path.join(*pathlist)153def readFile( filename ):154    log_lines = []155    if _exists( filename ):156        try:157            if sys.version_info >= (3, 0):158                with _open( filename, 'r') as thefile:159                    thedata = thefile.read()160            else:161                thefile = _open( filename, 'r' )162                thedata = thefile.read()163                thefile.close()164        except IOError:165            log_lines.append( 'unable to read data from ' + filename )166            return log_lines, ''167        except Exception as e:168            log_lines.append( 'unknown error while reading data from ' + filename )169            log_lines.append( e )170            return log_lines, ''171        return log_lines, thedata172    else:173        log_lines.append( '%s does not exist' % filename )174        return log_lines, ''175def renameFile ( thesource, thedest ):176    log_lines = []177    log_lines.append( 'renaming file %s to %s' % (thesource, thedest) )178    try:179        _rename( thesource, thedest )180    except IOError:181        log_lines.append( 'unable to rename %s to %s' % (thesource, thedest) )182        return False, log_lines183    except Exception as e:184        log_lines.append( 'unknown error while attempting to rename %s to %s' % (thesource, thedest) )185        log_lines.append( e )186        return False, log_lines187    return True, log_lines188def _remove_trailing_dot( thename, endreplace='' ):189    if thename[-1] == '.' and len( thename ) > 1 and endreplace != '.':190        return _remove_trailing_dot( thename[:-1] + endreplace )191    else:192        return thename193def setSafeName( thename, illegalchars='<>:"/\|?*', illegalreplace='_', endreplace='' ):194    loglines = []195    if not thename:196        loglines.append( 'name is empty, returning it' )197        return thename, loglines198    s_name = ''199    loglines.append( 'started with %s' % thename )200    loglines.append( 'the illegal characters are %s and the replacement is %s' % (illegalchars, illegalreplace) )201    for c in list( _remove_trailing_dot( thename, endreplace=endreplace ) ):202        if c in illegalchars:203            s_name = s_name + illegalreplace204        else:205            s_name = s_name + c206    loglines.append( 'finished with %s' % s_name )207    return s_name, loglines208def writeFile( data, filename, wtype='wb' ):209    log_lines = []210    if type(data).__name__=='unicode':211        data = data.encode('utf-8')212    try:213        if sys.version_info >= (3, 0):214            with _open( filename, wtype) as thefile:215                thefile.write( data )216        else:217            thefile = _open( filename, wtype )218            thefile.write( data )219            thefile.close()220    except IOError as e:221        log_lines.append( 'unable to write data to ' + filename )222        log_lines.append( e )223        return False, log_lines224    except Exception as e:225        log_lines.append( 'unknown error while writing data to ' + filename )226        log_lines.append( e )227        return False, log_lines228    log_lines.append( 'successfuly wrote data to ' + filename )...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
