前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现Linux环境下的ls命

Python实现Linux环境下的ls命

作者头像
py3study
发布2020-01-06 11:08:38
1.4K0
发布2020-01-06 11:08:38
举报
文章被收录于专栏:python3python3

在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))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档