Python实现Linux环境下的ls命令

来源:互联网 发布:阿里云 dns服务器地址 编辑:程序博客网 时间:2024/06/07 23:38

在Linux下使用ls命令结合正则表达式,能够高效地进行文件搜索,并通过参数操作文件,于是就想用Python实现这个功能以便在Windows上使用

import osimport reimport syspath = os.getcwd()substr = raw_input('The sub-string of the file (Support for Regular Expression): ')reg = r'' + substrcount = 0totalSize = 0fileList = os.listdir(path)def getFileSize(filePath):return os.path.getsize(filePath)def humanReadFileSize(fileByte):# fileByte = str(getFileSize(filePath))if fileByte == 0:return ''elif fileByte < 1024:# BfileSize = str(fileByte) + ' B'elif fileByte < 1024*1024:# KBfileSize = str(fileByte/1024.0) + ' KB'elif fileByte < 1024*1024*1024:# MBfileSize = str(fileByte/1024.0/1024.0) + ' MB'else:# GBfileSize = str(fileByte/1024.0/1024.0/1024.0) + ' GB'return fileSizefor fileName in fileList:if re.match(reg, fileName):count = count+1filePath = os.path.join(path, fileName)fileSize = getFileSize(filePath)totalSize = totalSize+fileSizeprint '\t', count, ' - ', humanReadFileSize(fileSize).ljust(30, ' '), fileNameprint '-'*160if len(sys.argv)!=1:if sys.argv[1] == 'remove':os.remove(filePath)print '\n\t\t%d file(s) in total, total size: %s' % (count, humanReadFileSize(totalSize))


0 0