Python脚本:按一定顺序更改当前文件夹下所有文件,并将原文件名与新文件名保存到txt中(空格分隔)

精简后的脚本:

import os

path = r'W:\xxx\xxxx'
pre_name = '20220224'
file_list = os.listdir(path)
count = 1
with open(os.path.join(path, 'save_name.txt'), "a+", encoding="utf-8" as f:
	for file in file_list:
		olddir = os.path.join(path, file)	# 原来的文件路径
		filename = os.path.splitext(file)[0]	# 文件名
		filetype = os.path.splitext(file)	# 文件扩展名
		str_name = "{}{:03}{}.format(pre_name, count, filetype)
		newdir = os.path.join(path, str_name)	# 新的文件路径
		os.rename(olddir, newdir)	# 重命名
		count += 1
		f.writelines("\""+file+"\"" + ' ' + "\"" + str_name + "\"" + '\n')

原来的:

from genericpath import exists
import os

# 当前工作路径
dir = os.getcwd()

# 改变到指定路径
dir = os.chdir(r'./fire')
path = '/data1/zcz/PythonRequest/fire'
file_list = os.listdir(path)
count = 1

if os.path.exists('../save_name.txt'):
    with open('../save_name.txt', mode='r', encoding='utf-8') as file:
        print(file.readlines())
        f = open('../save_name.txt','a')
else:
    with open("../save_name.txt", mode='w', encoding='utf-8') as file:
        print("文件创建成功")
        f = open('../save_name.txt','a')

for file in file_list:
    f.write(file + '\t\t')
    olddir=os.path.join(path, file)  # 原来的文件路径
           
    filename=os.path.splitext(file)[0]  # 文件名
    filetype=os.path.splitext(file)[1]  # 文件扩展名
    str_name = "20220223_" + str(count) + filetype
    newdir=os.path.join(path, str_name)  # 新的文件路径

    os.rename(olddir, newdir)  # 重命名

    count += 1
    f.write(str_name + '\n')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LEO-max

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值