2011-11-29 53 views
0

我是Python的新手,我创建了以下函数,根据列表中的项目(promptList)从目录(livepromptDir)复制文件)。到目前为止,它只将列表中的第一个项目复制到目标目录。请帮忙!提前致谢。如何从基于Python中的文件名列表中的项目目录复制文件

def copyItemToPrompt(): 
    #This function will copy all of the appropriate Voice Prompt files from LivePrompts directory to promptDir based on promptList 

    os.chdir(livepromptDir) 
    try: 
     for i in range(0,len(promptList)): 
      for filename in fnmatch.filter(os.listdir(livepromptDir), promptList[i]): 
       shutil.copy(filename, promptDir) 
      return 

    except Exception as error: 
     log(logFile, 'An error has occurred in the copyLiveToPrompt function: ' + str(error)) 
     raise 
+2

改变你回一个缩进背 – favoretti

回答

2

你要移动的returnfor循环,否则你的函数的第一个迭代后返回。事实上,你甚至不需要回报:

def copyItemToPrompt(): 
    """This function will copy all of the appropriate Voice Prompt files from LivePrompts directory to promptDir based on promptList""" 

    os.chdir(livepromptDir) 
    try: 
     for i in range(0,len(promptList)): 
      for filename in fnmatch.filter(os.listdir(livepromptDir), promptList[i]): 
       shutil.copy(filename, promptDir) 

    except Exception as error: 
     log(logFile, 'An error has occurred in the copyLiveToPrompt function: ' + str(error)) 
     raise 
+0

它的工作现在。非常感谢你。 –

0

正如@rcriii提到的,​​回报是什么是短路的功能。我不确定你想要完成什么,但我想你只是想从一个目录复制文件列表到另一个目录,给出一个glob模式列表。

如果是这样的话,并给你有这样的目录:

. 
├── a 
│   ├── file1 
│   ├── file2 
│   └── tmp3 
└── b 

这个功能应该给你一点更清洁的方式来做到这一点(的东西像for i in range...一般不使用像你在这里。)另外,如果您未能更改回来,更换目镜有时会给您未来的问题。

import shutil 
from itertools import chain 
from os import path 
from glob import glob 

def copy_with_patterns(src, dest, patterns): 
    # add src dir to given patterns 
    patterns = (path.join(src, x) for x in patterns) 

    # get filtered list of files 
    files = set(chain.from_iterable(glob(x) for x in patterns)) 

    # copy files 
    for filename in files: 
     shutil.copy(filename, filename.replace(src, dest)) 

调用这个函数是这样的:

copy_with_patterns('a', 'b', ['file*']) 

会让你的目录现在看起来是这样的:

. 
├── a 
│   ├── file1 
│   ├── file2 
│   └── tmp3 
└── b 
    ├── file1 
    └── file2 
+0

非常感谢您的帮助。 –

相关问题