python移动文件到另一个文件夹若有同名文件更改文件名_python – 将文件名匹配到foldernames然后移动文件...

我有名为“a1.txt”,“a2.txt”,“a3.txt”,“a4.txt”,“a5.txt”等文件.然后我有名为“a1_1998”,“a2_1999”,“a3_2000”,“a4_2001”,“a5_2002”等文件夹.

我想在文件“a1.txt”和&之间进行连接.文件夹“a1_1998”例如. (我猜我需要经常表达才能做到这一点).然后使用shutil将文件“a1.txt”移动到文件夹“a1_1998”,将文件“a2.txt”移动到文件夹“a2_1999”等….

我已经开始这样了,但是我因为对常规表达缺乏了解而陷入困境.

import re

##list files and folders

r = re.compile('^a(?P')

m = r.match('a')

m.group('id')

##

##Move files to folders

我稍微修改了下面的答案,使用shutil来移动文件,做了诀窍!

import shutil

import os

import glob

files = glob.glob(r'C:\Wam\*.txt')

for file in files:

# this will remove the .txt extension and keep the "aN"

first_part = file[7:-4]

# find the matching directory

dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0]

shutil.move(file, dir)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值