用python写linux中的ls,Python实现Linux环境下的ls命令

在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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值