返回顶部

常用的shell脚本

用python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径

#!/usr/bin/env python

import os

for root,dirs,files in os.walk('/tmp'):
 
    for name in files:
      
        print (os.path.join(root,name))

os.walk()

原型为:os.walk(top, topdown=True, onerror=None, followlinks=False)

 

我们一般只使用第一个参数。(topdown指明遍历的顺序)

 

该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。

第一个是路径,第二个是路径下面的目录,第三个是路径下面的非目录(对于windows来说也就是文件)

 

os.listdir(path)  

其参数含义如下。path 要获得内容目录的路径

 

请按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2013-09-23.log, 并且把磁盘的使用情况写到到这个文件中 

 

import time

import os

new_time = time.strftime('%Y-%m-%d')


# 返回的是一个列表
disk_status = os.popen('df -h').readlines()

# 把列表转换成字符串
str1 = ''.join(disk_status)

with open(new_time+'.log','w') as f:

    f.write('%s' % str1)

    f.flush()

    f.close()

 

posted @ 2018-04-09 09:58  Crazymagic  阅读(179)  评论(0编辑  收藏  举报