通过检查文件名中的string来重命名文件,将被相应的新stringreplace

我正在寻找通过用特定的新stringreplace某些string的所有实例来重命名大量的文件,但是有一大堆旧到新的对。 让我举个例子来帮助解释…

**Original List** abc_mno_pqr.txt def_mno_lmn.txt xyz_mno_efg.txt xyz_tuv_pqr.txt xyz_stu_bcd.txt fgh_efg_klm.txt Replace instances of: with: mno 345 xyz 123 efg 567 **Resulting List** abc_345_pqr.txt def_345_lmn.txt 123_345_567.txt 123_tuv_pqr.txt 123_stu_bcd.txt fgh_567_klm.txt 

这是相同的文字,但有丰富多彩的突出帮助。

我没有一个.bat文件或Python甚至Excel的偏好。 无论您想要做什么工具,我都会给它一个机会!

更新:我提供的解决scheme

我最终写在JavaScript中,因为我比Python更熟悉。 我所拥有的并不是一个一体化的解决scheme,但是它处理了繁重的工作。 感谢ettanany,他的解决scheme有助于将步骤/逻辑放在一起来完成这项工作。 我正在使用的实际文件名在命名结构上并不像我列出的那样一致,但是ettanany的答案肯定适用于我提供的。

 var mapping = {'mno': '345','xyz': '123','efg': '567'},result=[],newName=[], files = ['abc_mno_pqr.txt', 'def_mno_lmn.txt', 'xyz_mno_efg.txt', 'xyz_tuv_pqr.txt', 'xyz_stu_bcd.txt', 'fgh_efg_klm.txt']; for (var item = 0; item < files.length; item++) { // loop thru files var thisFile = files[item].split('_'); // split file into segments newName = []; // clear out newName array for (var i = 0; i < thisFile.length; i++) { // loop thru segments for (var key in mapping) { // loop thru mapping object if (key == thisFile[i]) { // if key and segment match var segment = mapping[key]; break; } else { var segment = thisFile[i]; } } newName.push(segment); // add segment to array } result.push(newName.join("_")); // add new filename to results /* With how my files actually are named, I knew I did not need to worry about removing/appending the file extension. */ } 

使用Python,您可以将旧的和新的值存储在字典中,并使用列表理解与split()函数为您的文件列表的每个项目如下所示:

 d = {'mno': '345', 'xyz': '123', 'efg': '567'} files = ['abc_mno_pqr.txt', 'def_mno_lmn.txt', 'xyz_mno_efg.txt', 'fgh_efg_klm.txt'] res = ['_'.join([item.split('_')[0], d[item.split('_')[1]], item.split('_')[2]]) for item in files] print(res) # Output: ['abc_345_pqr.txt', 'def_345_lmn.txt', 'xyz_345_efg.txt', 'fgh_567_klm.txt'] 

编辑:

我注意到也可能需要更改文件名的第一部分和最后一部分(不仅是第二部分),更通用的解决scheme如下所示:

 res = [] for item in files: new_item = [] for i in item[:-4].split('_'): if i in d: new_item.append(d[i]) else: new_item.append(i) res.append('_'.join(new_item) + '.txt') 

输出示例:

 >>> d = {'mno': '345', 'xyz': '123', 'efg': '567'} >>> files = ['def_mno_lmn.txt', 'xyz_mno_efg.txt', 'xyz_tuv_pqr.txt'] >>> >>> res = [] >>> for item in files: ... new_item = [] ... for i in item[:-4].split('_'): ... if i in d: ... new_item.append(d[i]) ... else: ... new_item.append(i) ... res.append('_'.join(new_item) + '.txt') ... >>> >>> files ['def_mno_lmn.txt', 'xyz_mno_efg.txt', 'xyz_tuv_pqr.txt'] >>> res ['def_345_lmn.txt', '123_345_567.txt', '123_tuv_pqr.txt'] 
    Interesting Posts