Python os模块常用函数


常用函数

  • 获取当前路径 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()

合并文件,类似于cat命令

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)

win系统下复制文件 shutil.copy命令

使用高级文件接口:shutil

src = "./1.txt"
dst = "E:"
shutil.copy(src, dst)   # 会发生覆盖

不建议使用 os.system 命令:

"""
- 路径分割必须是反斜杠!!!
- 相对路径或绝对路径都可以,跨盘复制也可以
- 文件存在则覆盖
"""
src = ".\\1.txt"
dst = "E:"
sh = "copy " + src + " " + dst
os.system(sh)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章