将文件夹中的文件复制到python中的一个目录中

Aar*_*ron 5 python copy file

我有一个文件夹,包含一些文件,我想复制一个目录(这个文件夹也有一些我不想复制的文件).我知道有os.chdir("..")命令将我移动到目录.但是,我不确定如何将我需要的文件复制到此目录中.任何帮助将不胜感激.


更新:

这就是我现在拥有的:

from shutil import copytree, ignore_patterns

copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Traceback (most recent call last):
  File "update.py", line 61, in <module>
    copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.py", line 146, in copytree
    os.makedirs(dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 17] File exists: '/Users/aaron/Desktop/'
Run Code Online (Sandbox Code Playgroud)

Chi*_*chi 8

shutil模块可以做到这一点,特别是copyfile,copy,copy2copytree功能.http://docs.python.org/library/shutil.html

你可能想要这些方面的东西:

import os
import shutil

fileList = os.listdir('path/to/source_dir')
fileList = ['path/to/source_dir/'+filename for filename in fileList]

for f in fileList:
    shutil.copy2(f, 'path/to/dest_dir/')
Run Code Online (Sandbox Code Playgroud)

您当然可以在调用期间过滤掉一些文件名os.listdir().例如,

fileList = [filename for filename in os.listdir('path/to/source_dir') if filename[-3] is '.txt']
Run Code Online (Sandbox Code Playgroud)

而不是fileList = os.listdir('path/to/source_dir')只获取.txt文件