5

I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into this directory. Any help would be greatly appreciated.


UPDATE:

This is what I have now:

from shutil import copytree, ignore_patterns

copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))

I am getting the following error:

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/'
Aaron
  • 2,672
  • 10
  • 28
  • 45
  • possible duplicate of [How do I copy a file in python?](http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python) – Felix Kling Jun 01 '10 at 16:51

1 Answers1

9

The shutil module can do this, specifically the copyfile, copy, copy2 and copytree functions. http://docs.python.org/library/shutil.html

You probably want something along these lines:

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/')

You can of course filter some file names out during the call to os.listdir(). For example,

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

instead of fileList = os.listdir('path/to/source_dir') to get just the .txt files

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
  • I took your advice and tried using copytree. For some reason, I'm getting an error when I try to run it. Please see what I added under my question. Thank you,Aaron – Aaron Jun 01 '10 at 18:57
  • 1
    `copytree` requires that the destination directory not already exist. – Kevin Horn Jun 01 '10 at 22:29
  • For the example you gave, would I need to do this for each filename? I see on line 5 you add the filename. Since I have 5 files that need to be copied how would that work. – Aaron Jun 01 '10 at 23:44
  • Yes, this will work for any number of files... That's what the `for` loops are for... – Chinmay Kanchi Jun 02 '10 at 10:42
  • Ok, so all I need to do is input the path to the source dir and destination. And it will pull all the files in the source directory? – Aaron Jun 02 '10 at 12:51