os.getcwd()
os.path.exists
os.path.isfile
os.mkdir
shutil.copy
os.path.join
自动选择 \ 或 /os.remove
import os, shutil
import re
def merge_files():
root = "."
xml_path = "./Annotations/"
if not os.path.exists(xml_path): # 目标路径不存在, 则创建
os.makedirs(xml_path)
jpg_path = "./Images/"
if not os.path.exists(jpg_path): # 目标路径不存在, 则创建
os.makedirs(jpg_path)
for root, dirs, files in os.walk(root,topdown = True):
for file in files:
file_path = os.path.join(root, file) # file是文件名, path是相对路径
if re.search("Annotations.*xml", file_path):
dst_path = os.path.join(xml_path, file)
if os.path.isfile(dst_path): pass # 文件不存在,则复制
else: shutil.copy(file_path, dst_path)
continue
if re.search("Image.*jpg", file_path):
dst_path = os.path.join(jpg_path, file)
if os.path.isfile(dst_path): pass
else: shutil.copy(file_path, dst_path)
merge_files()
file = "train.txt"
if os.path.exists(file):
os.remove(file)
with open(file, 'a') as w:
with open("2007_train.txt", 'r') as r:
txt = r.read()
w.write(txt)
with open("2007_val.txt", 'r') as r:
txt = r.read()
w.write(txt)
使用高级文件接口:shutil
src = "./1.txt"
dst = "E:"
shutil.copy(src, dst) # 会发生覆盖
不建议使用 os.system 命令:
"""
- 路径分割必须是反斜杠!!!
- 相对路径或绝对路径都可以,跨盘复制也可以
- 文件存在则覆盖
"""
src = ".\\1.txt"
dst = "E:"
sh = "copy " + src + " " + dst
os.system(sh)