ホームページ  >  記事  >  バックエンド開発  >  Pythonのディレクトリとファイル名の操作

Pythonのディレクトリとファイル名の操作

高洛峰
高洛峰オリジナル
2017-02-27 17:10:201469ブラウズ

1. 操作ディレクトリとファイル名

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import os,re
import shutil 
import time


listdirを使って検索

def search_OFD_old(my_pattern, diretory):
  try:
    names = os.listdir(diretory)    
  except os.error:
    print "error"
    return
  for name in names:
    fullname = os.path.normpath(os.path.join(diretory, name))
    if os.path.isfile(fullname):
      result = my_pattern.search(name)
      if result and name.lower().endswith("txt"):
        shutil.copy(fullname, dest_dir)      
    elif os.path.isdir(fullname):
      search_OFD(my_pattern, fullname)

walk関数を使って検索

def search_OFD(my_pattern, diretory):
  for root,dirs,files in os.walk(diretory):
    for filename in files:
      result = my_pattern.search(filename)
      if result and filename.lower().endswith("txt"):
        fullname = os.path.join(root, filename)
        shutil.copy(fullname, dest_dir)

存在しない場合は作成します。 :

if not os.path.isdir(dest_dir):
  os.makedirs(dest_dir)

Matching names

import re
pattern = re.compile("1ABC")
pattern.search(var)

Python のディレクトリとファイル名の操作に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。