zoukankan      html  css  js  c++  java
  • python创建和删除文件

    #!/usr/bin/python
    #-*-coding:utf-8-*-       #指定编码格式,python默认unicode编码
    
    import os
    directory = "./dir"
    os.chdir(directory)  #切换到directory目录
    cwd = os.getcwd()  #获取当前目录即dir目录下
    print("------------------------current working directory------------------")
    
    def deleteBySize(minSize):
        """删除小于minSize的文件(单位:K)"""
        files = os.listdir(os.getcwd())  #列出目录下的文件
        for file in files:
            if os.path.getsize(file) < minSize * 1000:
                os.remove(file)    #删除文件
                print(file + " deleted")
        return
    
    def deleteNullFile():
        '''删除所有大小为0的文件'''
        files = os.listdir(os.getcwd())
        for file in files:
            if os.path.getsize(file)  == 0:   #获取文件大小
                os.remove(file)
                print(file + " deleted.")
        return
    
    def create():
        '''根据本地时间创建新文件,如果已存在则不创建'''
        import time 
        t = time.strftime('%Y-%m-%d',time.localtime())  #将指定格式的当前时间以字符串输出
        suffix = ".docx"
        newfile= t+suffix
        if not os.path.exists(newfile):
            f = open(newfile,'w') 
            print newfile
            f.close()
            print newfile + " created."
        else:
            print newfile + " already existed."
        return
    hint = '''funtion:
                1   create new file
                2   delete null file
                3   delete by size
    please input number:'''
    while True:
        option = raw_input(hint)  #获取IO输入的值
        if cmp(option,'1') == 0:
            create()
        elif cmp(option,'2') == 0:
            deleteNullFile()
        elif cmp(option,'3') == 0:
            minSize = raw_input("minSize(K):")
            deleteBySize(minSize)
        elif cmp(option,'q') == 0:
            print "quit !"
            break
        else:
            print ("disabled input ,please try again....")
    

      

  • 相关阅读:
    Infopath Notify 弹出提示信息
    window.showModalDialog 返回值
    【转】获得正文内容中的所有img标签的图片路径
    Json Datable Convert
    Sharepoint 列表 附件 小功能
    Surgey 权限更改
    SQL 触发器用于IP记录转换
    Caml语句 查询分配给当前用户及当前组
    jquery 1.3.2 auto referenced when new web application in VSTS2010(DEV10)
    TFS diff/merge configuration
  • 原文地址:https://www.cnblogs.com/yuanqiangfei/p/8086044.html
Copyright © 2011-2022 走看看