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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章