search
HomeBackend DevelopmentPython TutorialPython复制目录结构脚本代码分享

引言

  有个需要,需要把某个目录下的目录结构进行复制,不要文件,当目录结构很少的时候可以手工去建立,当目录结构复杂,目录层次很深,目录很多的时候,这个时候要是还是手动去建立的话,实在不是一种好的方法,弄不好会死人的。写一个python脚本来处理吧。

首先了解

  写python脚本前,先了解几个东西

代码如下:


#!/usr/bin/python


这个东西写过脚本的人都知道,用来标明该脚本的执行器,类似的还有

代码如下:


#!/bin/bash       通过bash来执行
#!/usr/local/php/bin/php 通过php执行器来执行   
 

# -*- coding: utf-8 -*-


这个是设置脚本的编码格式,不然非英文可能会出现乱码

匿名函数lambda

代码如下:


#lambda很好用,创建匿名函数很方便
g = lambda x,y : x+y
g(3,5) #返回8


匿名函数分为四部分,标识 lambda,分号 :,参数 x,y,操作 x+y

除了这个之外,还有函数map、filter一个进行映射,一个进行过滤

代码如下:


__name__=="__main__"


一个文件就是一个模块,在python中每个模块都有一个__name__属性,属性的值取决于如何使用该模块,一般有两种使用方式,直接在命令行运行,这个时候__name__值为__main__,当import使用的时候,__name__值就是当前模块的名称(不带扩展名),因此可以通过这个判断是否是直接在命令行运行程序,以便做一些脚本使用。

代码如下:


import os
import sys


还有这两个模块,os包含一些操作系统功能,比如说遍历文件夹,拼接路径等等,sys模块包含系统函数,我这里只用来获取脚本后面的参数

编码

代码如下:


#!/usr/bin/python
# -*- coding: utf-8 -*-
#Filename:floders.py

import os
import sys

source = os.path.realpath(sys.argv[1])
target = os.path.realpath(sys.argv[2])

def isdir(x):
    return os.path.isdir(x) and x != '.svn'
def mkfloders(src,tar):
    paths = os.listdir(src)
    paths = map(lambda name:os.path.join(src,name),paths)
    paths = filter(isdir, paths)
    if(len(paths)         return
    for i in paths:
        (filepath, filename)=os.path.split(i)
        targetpath = os.path.join(tar,filename)
        not os.path.isdir(targetpath) and os.mkdir(targetpath)
        mkfloders(i,targetpath)

if __name__=="__main__":
    if(os.path.isdir(source)):
        if(target.find(source) == 0):
            print("不能将生成的新目录放在源目录下")
        else:
            if not os.path.isdir(target):
                os.mkdir(target)
            mkfloders(source,target)
    else:
        print("源文件夹不存在")

使用

  使用很简单:

代码如下:


#在当前文件夹下执行
./folders.py ./ /tmp/yyyyy

#执行完之后就会在/tmp下创建yyyyy目录,目录中包含上面的第一个文件夹中的目录结构

这个地方有两个要注意的地方,不能将创建后的目录放在要复制的目录中或者其子目录中

总结

  在做这个的时候遇到了这个问题 /usr/bin/python^M: bad interpreter: No such file or directory ,这个问题看样子是编码的问题,在每行后面添加了个字符,查资料后,原来是由于我从windows下直接把程序复制到linux下的编码出现了问题,解决方法很简单:vi folders.py之后,在命令行下输入

代码如下:


:set ff #结果表示编码平台,应该是fileformat=dos

:set fileformat=unix #设置编码到unix平台

:set ff #这个时候再去查看文件编码,应该是fileformat=unix

Statement
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
The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor