python學習- 列印最常用的10條linux命令和尋找目錄下重複的檔案

來源:互聯網
上載者:User

標籤:python

一、列印最常用的10條linux命令

#!/usr/bin/python#coding=utf-8import osfrom collections import Counterc = Counter()with open(os.path.expanduser('~/.bash_history')) as f:for line in f:cmd = line.strip().split()if cmd:c[cmd[0]]+=1print c.most_common(10)

效果如下:



二、找到目錄下重複的檔案

#!/usr/bin/python#coding=utf-8from __future__ import print_functionimport sysimport hashlibimport osimport fnmatchCHUNK_SIZE=8192def is_file_match(filename,patterns):for pattern in patterns:if fnmatch.fnmatch(filename,pattern):return Truereturn Falsedef find_specific_files(root,patterns=['*'],exclude_dirs=[]):for root,dirnames,filenames in os.walk(root):for filename in filenames:if is_file_match(filename,patterns):yield os.path.join(root,filename)for d in exclude_dirs:if d in dirnames:dirnames.remove(d)def get_chunk(filename):with open(filename) as f:while True:chunk=f.read(CHUNK_SIZE)if not chunk:breakelse:yield chunkdef get_file_checksum(filename):h=hashlib.md5()for chunk in get_chunk(filename):h.update(chunk)return h.hexdigest()def main ():sys.argv.append("")directory=sys.argv[1]if not os.path.isdir(directory):raise SystemExit ("{0} is not a directory".format(directory)) record={}for item in find_specific_files(directory):checksum=get_file_checksum(item)if checksum in record:print ('find duplicate files: {0} vs {1}'.format(record[checksum],item))else:record[checksum]=itemif __name__ == '__main__':main()

效果如下:

python學習- 列印最常用的10條linux命令和尋找目錄下重複的檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.