python目录与文件名操作例子

yipeiwu_com6年前Python基础

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)

匹配名称

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

相关文章

使用Python将Mysql的查询数据导出到文件的方法

mysql官方提供了很多种connector,其中包括python的connector。 下载地址在:http://dev.mysql.com/downloads/connector/p...

python+pyqt实现右下角弹出框

python+pyqt实现右下角弹出框

本文实例为大家分享了pyqt实现右下角弹出框的具体代码,供大家参考,具体内容如下 构造函数中: self.desktop=QDesktopWidget() self.move((...

Python将文字转成语音并读出来的实例详解

Python将文字转成语音并读出来的实例详解

前言 本篇文章主要介绍,如何利用Python来实现将文字转成语音。将文字转成语音主要有两种不同的实现方法:先将文字转成语音,然后再通过读取语音实现发音、直接调用系统内置的语音引擎实现发音...

Python函数中的可变长参数详解

Python函数中的可变长参数详解

一、Python函数中的参数 1、使用python的函数时,有参数类别,比如位置参数、关键字参数、可变长参数 2、位置参数、关键字参数很好理解,关键是可变长参数经常能见到,但是一直没有...

Python实现的最近最少使用算法

本文实例讲述了Python实现的最近最少使用算法。分享给大家供大家参考。具体如下: # lrucache.py -- a simple LRU (Least-Recently-Use...