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)

相关文章

python3.0 模拟用户登录,三次错误锁定的实例

python3.0 模拟用户登录,三次错误锁定的实例 实例如下所示: # -*- coding:utf-8 -*- #需求模拟用户登录,超过三次错误锁定不允许登陆 count...

Python如何通过subprocess调用adb命令详解

前言 本文主要给大家介绍了关于使用Python通过subprocess调用adb命令,subprocess包主要功能是执行外部命令(相对Python而言)。和shell类似。 换言之除...

python SQLAlchemy 中的Engine详解

python SQLAlchemy 中的Engine详解

先看这张图,这是从官方网站扒下来的。 Engine 翻译过来就是引擎的意思,汽车通过引擎来驱动,而 SQLAlchemy 是通过 Engine 来驱动,Engine 维护了一个连接池(...

pytorch实现mnist分类的示例讲解

torchvision包 包含了目前流行的数据集,模型结构和常用的图片转换工具。 torchvision.datasets中包含了以下数据集 MNIST COCO(用于图像标注和目标检测...

老生常谈python函数参数的区别(必看篇)

在运用python的过程中,发现当函数参数为list的时候,在函数内部调用list.append()会改变形参,与C/C++的不太一样,查阅相关资料,在这里记录一下。 python中id...