Python comes with re bugs, regex is recommended

Re.error: bad escape \L at

The reason is that python's built-in re has a problem. You can
modify it to regex.

Install regex

pip install regex

use

import regex as re

The key replacement code uses 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))

Replace the complete code

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")

Guess you like

Origin blog.csdn.net/qq_43373608/article/details/108772126