将文件夹中的文件复制到python中的一个目录 [英] Copy files in folder up one directory in python

查看:187
本文介绍了将文件夹中的文件复制到python中的一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,有几个文件,我想复制一个目录(这个文件夹也有一些文件,我不想复制)。我知道有os.chdir(..)命令将我移动到目录。但是,我不知道如何将这些文件,我需要到这个目录。非常感谢任何帮助。

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.

更新:

这是我现在的情况:

from shutil import copytree, ignore_patterns

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

我收到以下错误:

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


推荐答案

shutil 模块可以这样做,特别是 copyfile copy copy2 copytree 函数。 http://docs.python.org/library/shutil.html

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

你可以在调用 os.listdir()过程中过滤掉一些文件名。例如,

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']

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

这篇关于将文件夹中的文件复制到python中的一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆