-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.py
More file actions
173 lines (135 loc) · 5.5 KB
/
replace.py
File metadata and controls
173 lines (135 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import json
import os
import glob
def modify_image_paths(directory_path, new_path_template=None, keep_original_extension=True):
"""
灵活修改imagePath的脚本
Args:
directory_path: JSON文件所在目录
new_path_template: 新路径模板,支持占位符:
{filename} - 原文件名(不含扩展名)
{original_filename} - 原完整文件名
{extension} - 原扩展名
keep_original_extension: 是否保持原扩展名
"""
json_files = glob.glob(os.path.join(directory_path, "*.json"))
if not json_files:
print("未找到JSON文件")
return
print(f"找到 {len(json_files)} 个JSON文件")
for file_path in json_files:
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
old_path = data.get('imagePath', '')
if not old_path:
print(f"⚠ {os.path.basename(file_path)}: 未找到imagePath")
continue
# 提取文件名信息
original_filename = os.path.basename(old_path)
filename_without_ext = os.path.splitext(original_filename)[0]
original_extension = os.path.splitext(original_filename)[1]
# 生成新路径
if new_path_template:
new_path = new_path_template.format(
filename=filename_without_ext,
original_filename=original_filename,
extension=original_extension
)
else:
# 默认只保留文件名
if keep_original_extension:
new_path = original_filename
else:
new_path = filename_without_ext + ".jpg" # 默认改为jpg
# 更新数据
data['imagePath'] = new_path
# 保存文件
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"✓ {os.path.basename(file_path)}: '{old_path}' -> '{new_path}'")
except Exception as e:
print(f"✗ 处理失败 {file_path}: {e}")
def interactive_modify():
"""交互式修改模式"""
print("=== JSON文件imagePath批量修改工具 ===\n")
# 获取目录
directory = input("请输入JSON文件目录路径: ").strip()
if not os.path.exists(directory):
print("目录不存在!")
return
# 预览文件
json_files = glob.glob(os.path.join(directory, "*.json"))
if not json_files:
print("目录中没有JSON文件")
return
print(f"\n找到 {len(json_files)} 个JSON文件")
# 显示当前的imagePath示例
try:
with open(json_files[0], 'r', encoding='utf-8') as f:
sample_data = json.load(f)
current_path = sample_data.get('imagePath', 'N/A')
print(f"当前imagePath示例: {current_path}")
except:
print("无法读取示例文件")
print("\n请选择修改方式:")
print("1. 只保留文件名(保持原扩展名)")
print("2. 只保留文件名(改为指定扩展名)")
print("3. 自定义路径模板")
print("4. 直接设置固定路径前缀")
choice = input("\n请选择 (1-4): ").strip()
if choice == "1":
# 只保留文件名,保持扩展名
modify_image_paths(directory, keep_original_extension=True)
elif choice == "2":
# 只保留文件名,修改扩展名
new_ext = input("请输入新的扩展名 (如: .jpg): ").strip()
if not new_ext.startswith('.'):
new_ext = '.' + new_ext
template = "{filename}" + new_ext
modify_image_paths(directory, template, False)
elif choice == "3":
# 自定义模板
print("\n可用占位符:")
print(" {filename} - 文件名(不含扩展名)")
print(" {original_filename} - 完整原文件名")
print(" {extension} - 原扩展名")
print("\n示例模板:")
print(" images/{filename}.jpg")
print(" data/pics/{original_filename}")
print(" /home/user/dataset/{filename}{extension}")
template = input("\n请输入路径模板: ").strip()
modify_image_paths(directory, template, True)
elif choice == "4":
# 固定前缀
prefix = input("请输入路径前缀 (如: images/): ").strip()
keep_ext = input("保持原扩展名? (y/n): ").strip().lower() == 'y'
if keep_ext:
template = prefix + "{original_filename}"
else:
new_ext = input("请输入新扩展名 (如: .jpg): ").strip()
if not new_ext.startswith('.'):
new_ext = '.' + new_ext
template = prefix + "{filename}" + new_ext
modify_image_paths(directory, template, keep_ext)
else:
print("无效选择")
def quick_modify():
"""快速修改模式 - 命令行参数"""
import sys
if len(sys.argv) < 3:
print("用法: python script.py <目录路径> <新路径模板>")
print("示例: python script.py ./data 'images/{filename}.jpg'")
return
directory = sys.argv[1]
template = sys.argv[2]
if not os.path.exists(directory):
print(f"目录不存在: {directory}")
return
modify_image_paths(directory, template, True)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
quick_modify()
else:
interactive_modify()