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)
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27