要使用上一级的子文件夹名称重命名文件,可以根据操作系统和具体需求采用不同的方法。以下是几种常见的实现方式:
Python 提供了强大的文件和目录操作功能,可以方便地实现这一需求。以下是一个示例脚本:
import os
def rename_files_with_parent_folder_name(root_dir):
for foldername, subfolders, filenames in os.walk(root_dir):
parent_folder = os.path.basename(os.path.dirname(foldername))
for filename in filenames:
file_ext = os.path.splitext(filename)[1]
new_filename = f"{parent_folder}{file_ext}"
old_file_path = os.path.join(foldername, filename)
new_file_path = os.path.join(foldername, new_filename)
# 检查新文件名是否已存在,避免覆盖
if not os.path.exists(new_file_path):
os.rename(old_file_path, new_file_path)
print(f"Renamed: {old_file_path} -> {new_file_path}")
else:
print(f"Skipped (duplicate): {old_file_path}")
# 使用示例
root_directory = "/path/to/your/root_directory" # 替换为你的根目录路径
rename_files_with_parent_folder_name(root_directory)
说明:
os.walk
遍历指定根目录下的所有子目录和文件。os.path.basename(os.path.dirname(foldername))
获取上一级子文件夹的名称。os.rename
用于重命名文件。如果你使用的是 Unix 类系统,可以使用以下 Bash 脚本:
#!/bin/bash
ROOT_DIR="/path/to/your/root_directory" # 替换为你的根目录路径
find "$ROOT_DIR" -type f | while read -r file; do
parent_dir=$(dirname "$file")
grandparent_dir=$(dirname "$parent_dir")
new_name=$(basename "$grandparent_dir")$(path_extension "$file")
new_file="$parent_dir/$new_name"
if [ "$file" != "$new_file" ] && [ ! -e "$new_file" ]; then
mv "$file" "$new_file"
echo "Renamed: $file -> $new_file"
fi
done
path_extension() {
local file="$1"
case "$file" in
*.*)
echo ".$(basename "$file" | sed "s/^.*\.//")"
;;
*)
echo ""
;;
esac
}
说明:
find
命令遍历所有文件。dirname
和 basename
用于获取文件的上一级目录名称。在 Windows 系统中,可以使用 PowerShell 脚本来实现:
$rootDir = "C:\path\to\your\root_directory" # 替换为你的根目录路径
Get-ChildItem -Path $rootDir -Recurse -File | ForEach-Object {
$parentFolder = $_.DirectoryName | Split-Path -Parent | Split-Path -Leaf
$ext = [System.IO.Path]::GetExtension($_.FullName)
$newName = "$parentFolder$ext"
$newPath = Join-Path -Path $_.DirectoryName -ChildPath $newName
if ($_.FullName -ne $newPath -and -Not (Test-Path -Path $newPath)) {
Rename-Item -Path $_.FullName -NewName $newName
Write-Output "Renamed: $($_.FullName) -> $newPath"
}
}
说明:
Get-ChildItem
递归获取所有文件。Split-Path
用于提取上一级子文件夹名称。领取专属 10元无门槛券
手把手带您无忧上云