在linux下使用ls命令结合正则表达式,能够高效地进行文件搜索,并通过参数操作文件,于是就想用python实现这个功能以便在windows上使用 import os import re import sys path = os.get
在linux下使用ls命令结合正则表达式,能够高效地进行文件搜索,并通过参数操作文件,于是就想用python实现这个功能以便在windows上使用
import os
import re
import sys
path = os.getcwd()
substr = raw_input('The sub-string of the file (Support for Regular Expression): ')
reg = r'' + substr
count = 0
totalSize = 0
fileList = 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:
# B
fileSize = str(fileByte) + ' B'
elif fileByte < 1024*1024:
# KB
fileSize = str(fileByte/1024.0) + ' KB'
elif fileByte < 1024*1024*1024:
# MB
fileSize = str(fileByte/1024.0/1024.0) + ' MB'
else:
# GB
fileSize = str(fileByte/1024.0/1024.0/1024.0) + ' GB'
return fileSize
for fileName in fileList:
if re.match(reg, fileName):
count = count+1
filePath = os.path.join(path, fileName)
fileSize = getFileSize(filePath)
totalSize = totalSize+fileSize
print '\t', count, ' - ', humanReadFileSize(fileSize).ljust(30, ' '), fileName
print '-'*160
if 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))
--结束END--
本文标题: Python实现Linux环境下的ls命
本文链接: https://lsjlt.com/news/191620.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0