通过首字母移动文件的 PowerShell、Python 或其他脚本语言

2 投票
5 回答
1884 浏览
提问于 2025-04-16 16:43

我需要一个脚本,可以递归地遍历 c:\somedir\ 这个文件夹,然后把文件移动到 c:\someotherdir\x\ 这个文件夹里,其中 x 是文件名的首字母。

有人能帮忙吗?


最后我得到了这个:

import os
from shutil import copy2
import uuid
import random

SOURCE = ".\\pictures\\"
DEST = ".\\pictures_ordered\\"

for path, dirs, files in os.walk(SOURCE):
    for f in files:
        print(f)
        starting_letter = f[0].upper()
        source_path = os.path.join(path, f)
        dest_path = os.path.join(DEST, starting_letter)

        if not os.path.isdir(dest_path):
            os.makedirs(dest_path)

        dest_fullfile = os.path.join(dest_path, f)

        if os.path.exists(dest_fullfile):            
            periodIndex = source_path.rfind(".")
            renamed_soruce_path = source_path[:periodIndex] + "_" + str(random.randint(100000, 999999))  + source_path[periodIndex:]
            os.rename(source_path, renamed_soruce_path)
            copy2(renamed_soruce_path, dest_path)            
            os.remove(renamed_soruce_path)
        else:
            copy2(source_path, dest_path)
            os.remove(source_path)`

5 个回答

2

这段代码的意思是:在C盘的某个文件夹(somedir)里,查找所有的文件(包括子文件夹里的文件),然后把这些文件移动到另一个文件夹(someotherdir)里。移动的时候,会根据文件名的第一个字母来放置文件。

具体步骤是这样的:

  • 首先,使用`ls`命令列出指定文件夹里的所有内容。
  • 然后,使用`?`来过滤,只保留那些不是文件夹的文件。
  • 接着,使用`mv`命令把这些文件移动到新的文件夹中,新的文件夹的名字是文件名的第一个字母。

最后,`-whatif`这个部分是用来模拟这个操作的,意思是“如果我真的执行这个命令,会发生什么”,但实际上并不会真的移动文件。

3

我猜这个在PowerShell里可以用。

gci -path c:\somedir -filter * -recurse |
    where { -not ($_.PSIsContainer) } |
    foreach { move-item -path $_.FullName -destination $_.Substring(0, 1) }
3

这里有一个简单的脚本,可以完成你想要的功能。它不会告诉你正在做什么,如果有两个同名的文件,它会直接覆盖掉旧的那个文件。

import os
from shutil import copy2

SOURCE = "c:\\source\\"

DEST = "c:\\dest\\"

# Iterate recursively through all files and folders under the source directory
for path, dirs, files in os.walk(SOURCE):
    # For each directory iterate over the files
    for f in files:
        # Grab the first letter of the filename
        starting_letter = f[0].upper()
        # Construct the full path of the current source file
        source_path = os.path.join(path, f)
        # Construct the destination path using the first letter of the
        # filename as the folder
        dest_path = os.path.join(DEST, starting_letter)
        # Create the destination folder if it doesn't exist
        if not os.path.isdir(dest_path):
            os.makedirs(dest_path)
        # Copy the file to the destination path + starting_letter
        copy2(source_path, dest_path)

撰写回答