麻烦的递归python文件复制程序

时间:2012-11-30 16:57:23

标签: python search recursion operating-system

我最近开始学习python并且遇到了一些麻烦。有问题的函数试图从给定的直接开始,在我的例子中,'/ home / jesse / ostest',搜索所有子目录,并将所有'.txt'文件复制到'/ home / jesse / COPIES ”。当我运行该程序时,一些文件被coppied但它陷入无限循环。当它变为'/ home / jesse'时(第10行搜索()),我希望它能够中断。也许我不太了解递归,但感谢帮助。

这是一个测试目录,带有用于测试程序的子目录。

[jesse@jesse ostest]$ tree
.
├── readme.txt
├── README_WxPython.txt
├── rect.txt
├── RELEASE_NOTES.txt
├── scrap.txt
├── sndarray.txt
├── sprite.txt
├── surface.txt
├── surfarray.txt
├── test_oo.txt
├── tests.txt
├── this
│   ├── gme_notes.txt
│   ├── gme_readme.txt
│   ├── h1.txt
│   ├── h2.txt
│   ├── how_to_build.txt
│   ├── howto_release_pygame.txt
│   ├── image.txt
│   ├── IMPORTANT_MOVED.txt
│   ├── index.txt
│   ├── install.txt
│   ├── is
│   │   ├── a
│   │   │   ├── color.txt
│   │   │   ├── common.txt
│   │   │   ├── cursors.txt
│   │   │   ├── dec.txt
│   │   │   ├── defs.txt
│   │   │   └── display.txt
│   │   ├── event.txt
│   │   ├── examples.txt
│   │   ├── filepaths.txt
│   │   ├── font.txt
│   │   ├── freetype.txt
│   │   ├── gfxdraw.txt
│   │   ├── gme_design.txt
│   │   └── path
│   │       ├── api.txt
│   │       ├── auth.txt
│   │       ├── camera.txt
│   │       ├── cdrom.txt
│   │       ├── cert_override.txt
│   │       ├── changes_for_symbian.txt
│   │       └── CHANGES.txt
│   └── joystick.txt
├── time.txt
├── TODO.txt
└── transform.txt

4 directories, 45 files

以下是代码:

def copyAll():
    print('This function attempts to search through /home/jesse/ostest and copy all .txt files.')
    input('Press <enter> to begin..')
    new = '/home/jesse/COPIES'
    os.mkdir(new)
    done = []
    search('/home/jesse/ostest', new, done)
    print(os.getcwd())
    print(os.listdir())

def search(arg, new, done):
    os.chdir(arg)
    print(os.getcwd())
    for var in os.listdir():
        if os.path.isdir(var) and var not in done:
            search(var, new, done)
        elif var[-4:] == '.txt' and var not in done:
            shutil.copy2(var, '/home/jesse/COPIES')
            print('COPIED', var, '\t\tto', new)
        elif os.getcwd() == '/home/jesse':
            break
        else:
            done += os.getcwd()
            os.chdir('..')
            search(os.getcwd(), new, done)

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

我现在已经开始工作了。

新代码:

def copyAll():
    print('Copy all files from a heirarchy.')
    tar = input('Enter a directory to start from: ')
    new = '/home/jesse/COPIES'
    os.mkdir(new)
    for root, dirs, files, in os.walk(tar):
        for file in files:
            if file[-4:] == '.txt':
                shutil.copy2(root+'/'+file, new)
                print('COPIED', file, '\t\tto', new)

我输入了'/'作为tar,并在收到错误之前复制了650多个文件!现在只需修复错误。