简体   繁体   English

如何根据 Folder2 文件名重命名 Folder1 中的文件?

[英]How to Rename Files from Folder1 Based On Folder2 files names?

I have 1000+ files in 2 folders(same amount).我在 2 个文件夹中有 1000 多个文件(数量相同)。

EXAMPLE例子

Folder1/
   0.json
   1.json
   2.json

Folder2/
   some_name1.xml
   some_name2.xml
   some_name3.xml

I want to rename all files in 1st folder based on second folder file names BUT NOT THE EXTENSIONS我想根据第二个文件夹文件名重命名第一个文件夹中的所有文件,但不是扩展

I got this script.我得到了这个脚本。 It must just rename all files one by one But now it got a problem, after renaming files there are shuffled which means information are not same as files in folder1.它必须只是一个一个地重命名所有文件但是现在它遇到了一个问题,重命名文件后有混洗,这意味着信息与文件夹1中的文件不同。 Any ideas how to fix that?任何想法如何解决这个问题?

from pathlib import Path

src = Path(r"/home/folder2")
dst = Path(r"/home/folder1")
for s, d in zip(src.iterdir(), dst.iterdir()):
    d.rename(d.with_name(s.with_suffix(d.suffix).name))

The following is an example of a key function that will use the first integer found within a file name as the sort key, otherwise just the file name (all files that do not contain integers within their file names will come last in the sort):以下是键 function 的示例,它将使用在文件名中找到的第一个 integer 作为排序键,否则仅使用文件名(所有文件名中不包含整数的文件将排在最后):

from pathlib import Path
import re
import math

rex = re.compile(r'\d+')
def my_key_function(path):
    m = rex.search(path.name)
    # file names without integers in them will be sorted last:
     return (int(m[0]) if m else math.inf, path.name)

for s, d in zip(sorted(src.iterdir(), key=my_key_function()), sorted(dst.iterdir(), key=my_key_function)):
    etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM