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
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor