文件批量重命名

注意:本文只提供代码,思路请自行阅读注释并查阅相关资料

要求如下:

文件夹不改名;每个文件的后缀名不变;名字改为该文
件的创建或修改日期(注意文件名的合法字符);如果多个文件重名,可以延长名字
(例如添加一个长度为 n 的随机字符串)
代码如下:
import os
import time
import random

# 获取文件的时间属性
# 用到的知识
#   os.getcwd() 方法用于返回当前工作目录
#   os.path.getatime(file) 输出文件访问时间
#   os.path.getctime(file) 输出文件的创建时间
#   os.path.getmtime(file) 输出文件最近修改时间
'''
times = fileTime(os.getcwd())
print(times)
print(type(times))

time.ctime(os.path.getatime(file)),
time.ctime(os.path.getmtime(file)),
time.ctime(os.path.getctime(file))
'''
def fileTime(file):
    return time.ctime(os.path.getmtime(file))


# 创建一个txt文件,文件名为mytxtfile,并向文件写入msg
def text_create(name):          # path:新创建的txt文件的存放路径
    savepath = name + '.txt'      # 也可以创建一个.doc的word文档
    file = open(savepath,'w')
    meg = fileTime(os.getcwd())   # 获取文件创建时间
    file.write(meg)               # 写入文件创建时间
    file.close()

# 批量创建文件
'''
i:创建文件数
path:创建路径
'''
def create_text(i):
    for a in range(i):
        a = str(a)
        name = "test" + a
        text_create(name)
    print("创建成功!")

# 读取文件内容,并修改文件名
def read(num):
    for a in range(num):
        a = str(a)
        name = "test" + a + '.txt'
        file = name
        temp = random.randint(1,100)
        a = time.strftime("%Y-%m-%d %H_%M",time.localtime(os.path.getctime(file)))
        text = str(temp) + ' ' + a + '.txt' 
        os.rename(name,text)
    print("修改成功!")
    
if __name__ == '__main__':
    print("当前工作路径:",os.getcwd())                     # 当前工作路径文件所在路径
    os.chdir("test2")                                      # 改变工作路径,需要提前创建好test2文件夹。注意必须在当前工作路径下创建test2,否则请自行指定路径
    print("改变当前工作路径后:",os.getcwd())                # 打印更改后的工作路径,确保无误再进行下一步
    while True:
        ch = input("1.批量创建文件.\n2.批量修改文件名为创建日期.\n3.退出程序.\n请选择功能:")
        if ch == '1':
            create_text(10)            # 批量创建10个文件
        elif ch == '2':
            read(10)
        elif ch == '3':
            break                       # 退出
        else:
            print("请输入正确的数字!!!")

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值