Python创建删除文件

Python代码如下:

复制代码
import os
directory = "E:\\学习日志\\"
os.chdir(directory) # 改变当前工作目录
cwd = os.getcwd() # 查看当前工作目录
print("--------------current working directory : " + cwd + "----------")

def deleteBySize(minSize):
    """删除小于minSize的文件(单位:K)"""
    files = os.listdir(os.getcwd()) # 列出目录中文件
    for file in files:
    ##    print file + " : " + str(os.path.getsize(file))
        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: #得到文件大小,如果是目录返回0
            os.remove(file)
            print(file + " deleted")
    return

def create():
    '''根据本地时间创建新文件,如果已存在则不创建'''
    import time
    #将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出
    t = time.strftime('%Y-%m-%d',time.localtime()) 
    suffix = ".docx"
    newFile =os.getcwd() + "\\" + t + suffix 
    if not os.path.exists(newFile):
        f = open(newFile,'w')
        f.close()
        print newFile + " created."
    else:
        print newFile + " already exist."
    return

hint = '''funtion : 
        1    create new file
        2    delete null file
        3    delete by size
        q    quit\n
please input number: '''
while True:
    option = raw_input(hint)
    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...")
复制代码

 

主要涉及到的就是一些文件操作函数和时间函数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值