Home > Backend Development > Python Tutorial > Python directory and file name operations

Python directory and file name operations

高洛峰
Release: 2017-02-27 17:10:20
Original
1534 people have browsed it

1. Operation directory and file name

##

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

import os,re
import shutil 
import time
Copy after login


##Search using 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)
Copy after login

Use the walk function to search

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)
Copy after login

If the directory does not exist, create it:

if not os.path.isdir(dest_dir):
  os.makedirs(dest_dir)
Copy after login

Matching names

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

For more articles related to python directory and file name operations, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template