python目录与文件名操作例子

yipeiwu_com5年前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彻底删除文件夹及其子文件方式

我就废话不多说了,直接上代码吧! #coding:utf-8 import os import stat import shutil #filePath:文件夹路径 def...

python 对类的成员函数开启线程的方法

如下所示: # -*- coding: utf-8 -*- import threading import thread import time class Test(objec...

Python3指定路径寻找符合匹配模式文件

本文实例讲述了Python3指定路径寻找符合匹配模式文件。分享给大家供大家参考。具体实现方法如下: 这里给定一个搜索路径,需要在此目录中找出所有符合匹配模式的文件 import g...

详解Python使用Plotly绘图工具,绘制甘特图

详解Python使用Plotly绘图工具,绘制甘特图

今天来讲一下如何使用Python 的绘图工具Plotly来绘制甘特图的方法 甘特图大家应该了解熟悉,就是通过条形来显示项目的进度、时间安排等相关情况的。 我们今天来学习一下,如何使用pl...

SQLite3中文编码 Python的实现

读取十万多条文本写入SQLite类型数据库,由于文本中存在中文字符,插入到数据库没错,取出时一直是UnicodeDecodeError,导致折腾了一天。 最后的解决方法: Python连...