使用 Python 修剪过长的目录和文件名
此 Python 脚本接受一个目录路径,然后扫描其中的每个文件和子目录,查找超过指定长度的任何文件名或目录名。找到后,脚本将这些名称截断以适应所需长度,并附加省略号(如 ...)以指示截断。此脚本的美妙之处在于其可配置性和嵌入的安全功能。
***注意:使用此脚本会丢失信息(因为新文件名会更短,文件名其余部分中的任何重要信息将永远丢失)。***此外,它可能以其他方式丢失信息。即使我们已仔细测试,它仍可能以意想不到的方式破坏你的数据。使用
如何使用
脚本提供以下命令行选项:
FixLongFilenames_usage.txt
usage: FixLongFilenames.py [-h] [-n LENGTH] [--ellipsis ELLIPSIS] [--dry] directory
Shorten long filenames and directory names.
positional arguments:
directory The directory to process.
options:
-h, --help show this help message and exit
-n LENGTH, --length LENGTH
The maximum allowable length for directory or file names.
--ellipsis ELLIPSIS The ellipsis to use when shortening.
--dry Dry run mode, only log what would be renamed without actual renaming.源代码
FixLongFilenames.py
#!/usr/bin/env python3
import os
import argparse
def shorten_path(path, max_length, ellipsis, dry_run):
if os.path.isdir(path):
base_name = os.path.basename(path)
if len(base_name) > max_length:
new_name = base_name[:max_length] + ellipsis
new_path = os.path.join(os.path.dirname(path), new_name)
if not os.path.exists(new_path):
if dry_run:
print(f"[DRY RUN] Directory would be renamed: {path} -> {new_name}")
else:
os.rename(path, new_path)
print(f"Renamed directory: {path} -> {new_name}")
return new_path
else:
base_name, ext = os.path.splitext(os.path.basename(path))
if len(base_name) > max_length:
new_name = base_name[:max_length] + ellipsis + ext
new_path = os.path.join(os.path.dirname(path), new_name)
if not os.path.exists(new_path):
if dry_run:
print(f"[DRY RUN] File would be renamed: {path} -> {new_name}")
else:
os.rename(path, new_path)
print(f"Renamed file: {path} -> {new_name}")
return new_path
return path
def iterate_and_shorten(directory, max_length, ellipsis, dry_run):
for root, dirs, files in os.walk(directory, topdown=False):
for dname in dirs:
dpath = os.path.join(root, dname)
shortened_path = shorten_path(dpath, max_length, ellipsis, dry_run)
dirs[dirs.index(dname)] = os.path.basename(shortened_path)
for fname in files:
fpath = os.path.join(root, fname)
shorten_path(fpath, max_length, ellipsis, dry_run)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Shorten long filenames and directory names.")
parser.add_argument('directory', help="The directory to process.")
parser.add_argument('-n', '--length', type=int, default=100, help="The maximum allowable length for directory or file names.")
parser.add_argument('--ellipsis', default="...", help="The ellipsis to use when shortening.")
parser.add_argument('--dry', action="store_true", help="Dry run mode, only log what would be renamed without actual renaming.")
args = parser.parse_args()
iterate_and_shorten(args.directory, args.length, args.ellipsis, args.dry)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow