Python directory and filename operation example _python

Source: Internet
Author: User

1. Operation directory and filename

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

import os,re import
shutil 
import Time

Search with Listdir

def search_ofd_old (My_pattern, diretory):
  try:
    names = Os.listdir (diretory)    
  except Os.error:
    print Error '
    return
  to 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)

Search using Walk function

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)

Directory does not exist, it is created:

If not Os.path.isdir (dest_dir):
  os.makedirs (Dest_dir)

Match Name

Import re Pattern
= Re.compile ("1ABC")
Pattern.search (Var)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.