![](/img/trans.png)
[英]Python : How to call csv files from the directory based on the list of items?
[英]How to copy files from a directory based on items in a list of filenames in Python
我是Python的新手,我已经创建了以下函数,用于根据列表(promptList)中的项目从目录(livepromptDir)复制文件。 到目前为止,它仅将列表中的第一项复制到目标目录。 请帮忙! 提前致谢。
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
您想将return
移到for
循环之外,否则函数将在第一次迭代后返回。 实际上,您甚至不需要返回:
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
如@rcriii所述,返回值是使函数短路的原因。 我不确定您要完成的工作,但是我认为您只想将给定的glob模式列表从一个目录复制文件到另一个目录。
如果是这样,并给你一个这样的目录:
.
├── a
│ ├── file1
│ ├── file2
│ └── tmp3
└── b
此功能应该为您提供一种更简洁的方法(例如for i in range...
东西for i in range...
通常不像您在这里那样使用。)此外,更改dirs有时在将来如果您无法更改会给您带来问题背部。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.