在Python中将文件夹中的文件复制到上一级目录
我有一个文件夹,里面有一些文件,我想把它们复制到上一级目录(这个文件夹里还有一些我不想复制的文件)。我知道可以用 os.chdir("..") 命令来切换到上一级目录。但是,我不太确定怎么把我需要的文件复制到这个目录里。希望能得到一些帮助。
更新:
这是我现在的代码:
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/'
1 个回答
9
这个 shutil
模块可以帮你完成这个任务,里面有几个函数,比如 copyfile
、copy
、copy2
和 copytree
。你可以在这里找到详细的说明: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/')
当然,在调用 os.listdir()
时,你可以过滤掉一些文件名。例如,
fileList = [filename for filename in os.listdir('path/to/source_dir') if filename[-3] is '.txt']
如果你只想获取 .txt
文件,而不是用 fileList = os.listdir('path/to/source_dir')
这样获取所有文件