报错 re.error: bad escape \L at
原因 python 自带的 re 有问题
修改成 regex 即可
安装 regex
pip install regex
使用
import regex as re
关键替换代码 使用 re.sub
str_des_file_0 = re.sub('(?s)<name>.*</name>', r"<name>w</name>", str_file)
images_dir_path = "D:/voc2007/JPEGImages/"
image_path = os.path.join(images_dir_path, i)
path_str = r"<path>{}</path>".format(image_path)
# print(path_str)
str_des_file_1 = re.sub('(?s)<path>.*</path>', path_str, str(str_des_file_0))
替换完整代码
import os, shutil
import regex as re
def mv_floder(path):
dir_abs_path = os.path.abspath(path)
res_dir = os.path.dirname(dir_abs_path)
res_dir = os.path.join(res_dir, "voc2007")
if os.path.exists(res_dir):
shutil.rmtree(res_dir)
os.mkdir(res_dir)
annotations_dir = os.path.join(res_dir, "Annotations")
if not os.path.exists(annotations_dir):
os.mkdir(annotations_dir)
JPEGImages_dir = os.path.join(res_dir, "JPEGImages")
if not os.path.exists(JPEGImages_dir):
os.mkdir(JPEGImages_dir)
print(dir_abs_path)
for root, y, files in os.walk(dir_abs_path):
for i in files:
file_path = os.path.join(root, i)
if root.find("annotations") != -1 or root.find("Annotations") != -1:
des_file_path = os.path.join(res_dir, "Annotations")
des_file_path = os.path.join(des_file_path, i)
with open(file_path, "r", encoding="utf8") as f:
str_file = f.read()
# print(str_file)
str_des_file_0 = re.sub('(?s)<name>.*</name>', r"<name>w</name>", str_file)
images_dir_path = "D:/voc2007/JPEGImages/"
image_path = os.path.join(images_dir_path, i)
path_str = r"<path>{}</path>".format(image_path)
# print(path_str)
str_des_file_1 = re.sub('(?s)<path>.*</path>', path_str, str(str_des_file_0))
with open(des_file_path, "w", encoding="utf8") as f_des:
# print(str_des_file)
f_des.write(str_des_file_1)
# shutil.copyfile(file_path, des_file_path)
if root.find("JPEGImages") != -1:
des_file_path = os.path.join(res_dir, "JPEGImages")
des_file_path = os.path.join(des_file_path, i)
shutil.copyfile(file_path, des_file_path)
if __name__ == "__main__":
mv_floder("./20200903-1jieguo")
mv_floder("./20200903-2")