3

我最近开始学习 python 并且遇到了一些麻烦。有问题的函数尝试从给定目录开始,在我的例子中,'/home/jesse/ostest',搜索所有子目录,并将所有'.txt'文件复制到'/home/jesse/COPIES '。当我运行该程序时,会复制一些文件,但它会陷入无限循环。我希望它在更改为“/home/jesse”(search() 的第 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)
4

2 回答 2

1

首先看一下 os.walk():

http://docs.python.org/2/library/os.html#os.walk

于 2012-11-30T16:59:24.427 回答
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 多个文件,然后出现错误!现在只需要修复错误。

于 2012-12-02T01:11:47.610 回答