python文件怎么重命名_Python文件重命名

我的目录中有一些文件,

file_IL.txt

file_IL.csv

file_NY.txt

file_NY.csv

我将不得不重命名它们,以便它们获得序列号.例如,

file_IL.txt_001

file_IL.csv_001

file_NY.txt_002

file_NY.csv_002

我编写了以下Python代码

def __init__(self):

self.indir = "C:\Files"

def __call__(self):

found = glob.glob(self.indir + '/file*')

length = len(glob.glob(self.indir + '/file*'))

print length

count = 000

for num in (glob.glob(self.indir + '/file*')):

count = count + 1

count = str(count)

print count

shutil.copy(num, num+'_'+count)

print num

count = int(count)

但这给了我如下结果

file_IL.txt_001

file_IL.csv_002

file_NY.txt_003

file_NY.csv_004

有人可以帮我修改上面的Python脚本以满足我的要求吗?我是Python的新手,我不确定如何实现它.

解决方法:

最好的方法是将扩展名存储并在字典中对该扩展名进行计数.

def __call__(self):

found = glob.glob(self.indir + '/file*')

length = len(found)

counts = {}

for num in found:

ext = num.rsplit(".",1)[-1] # Right split to get the extension

count = counts.get(ext,0) + 1 # get the count, or the default of 0 and add 1

shutil.copy(num, num+'_'+'%03d' % count) # Fill to 3 zeros

counts[ext] = count # Store the new count

标签:python

来源: https://codeday.me/bug/20191012/1903782.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值