只需要将下面内容运行前 修改文件夹路径(控制修改范围的文件名
不需要的话 就随便写一个不相同的文件名 就行 需要的话就是在这个文件名字之前的会被修改)
import os
import time
# 文件夹路径
image_directory = r"C:\Users\Lenovo\Desktop\新建文件夹\images" # 替换为你的图片文件夹路径
labels_directory = r"C:\Users\Lenovo\Desktop\新建文件夹\labels" # 替换为你的标签文件夹路径
# 控制修改范围的文件名
modify_up_to_file = "11 .txt" # 指定只修改文件名在 "5.txt" 之前的文件
def get_txt_files(directory):
return sorted(
[f for f in os.listdir(directory) if f.endswith('.txt') and f[0].isdigit()],
key=lambda x: int(x.split('.')[0])
)
def get_image_files(directory):
return sorted(
[f for f in os.listdir(directory) if f.lower().endswith(('.png', '.jpg', '.jpeg')) and f[0].isdigit()],
key=lambda x: int(x.split('.')[0])
)
def initialize_txt_files():
# 确保标签目录存在
if not os.path.exists(labels_directory):
os.makedirs(labels_directory)
# 获取所有图片文件
image_files = get_image_files(image_directory)
# 为每个图片创建对应的txt文件(如果不存在)
for img_file in image_files:
txt_name = os.path.splitext(img_file)[0] + '.txt'
txt_path = os.path.join(labels_directory, txt_name)
if not os.path.exists(txt_path):
with open(txt_path, 'w') as f:
pass # 创建空文件
# 初始化txt文件
initialize_txt_files()
# 保存文件的最后修改时间
last_modified_times = {}
# 初始化文件的最后修改时间
for filename in get_txt_files(labels_directory):
filepath = os.path.join(labels_directory, filename)
last_modified_times[filename] = os.path.getmtime(filepath)
print("开始监视文件变化...")
while True:
try:
# 获取当前文件列表
txt_files = get_txt_files(labels_directory)
# 找到指定文件的索引
modify_up_to_index = txt_files.index(modify_up_to_file) if modify_up_to_file in txt_files else len(txt_files)
for i in range(modify_up_to_index): # 只处理指定文件之前的文件
filename = txt_files[i]
filepath = os.path.join(labels_directory, filename)
# 检查文件的最后修改时间
current_modified_time = os.path.getmtime(filepath)
if current_modified_time != last_modified_times.get(filename, 0):
# 文件已被修改
print(f"{filename} 被修改")
# 复制内容到下一个文件
if i + 1 < modify_up_to_index: # 确保不复制到指定文件及其之后的文件
next_filename = txt_files[i + 1]
next_filepath = os.path.join(labels_directory, next_filename)
print(f"正在复制内容到 {next_filename}")
with open(filepath, 'r') as source_file:
content = source_file.read()
with open(next_filepath, 'w') as dest_file:
dest_file.write(content)
# 更新最后修改时间
last_modified_times[filename] = current_modified_time
break # 复制后跳出循环,防止连锁反应
except Exception as e:
print(f"发生错误: {str(e)}")
time.sleep(1)
continue
# 等待一段时间再检查
time.sleep(1) # 每秒检查一次