使用python将文件复制到与文件名称几乎相同的文件夹

时间:2014-04-13 11:12:37

标签: python copy

我会尝试解释我尝试做什么,但英语不是我的第一语言。

我有一个项目列表,例如["cat size", "house size", "car size"] 以及一些包含列表中项目名称的文件。例如cat.size.txthouse.size.fromBob.txt

我想要执行以下副本:cat.size.txt直接H:/new/2CopyTo/Cat size/house.size.fromBob.txt到目录H:/new/2CopyTo/house size/

下面是我将文件复制到一个目录的方法,但我希望每个文件都在自己的目录中(在我的电脑上,列表包含50个项目,所以不要手动完成)。 / p>

谢谢!

import glob
import shutil
import os

#=========List of items
list = ["cat size","house size","car size"]

#=========directories
FromDir = "H:/New/1RecievedFiles/"
CopyDir = "H:/New/2CopyTo/"

#=========get list of items to be used in glob.glob
filesList = [x.replace(" ", "*")+"*.*" for x in list]

#=========get list of new files in FromDir, use filesList in glob.glob
listOfNew = [glob.glob(FromDir+item) for item in filesList ]
# returns [['H:/New/1RecievedFiles\\cat.size.txt'], ['H:/New/1RecievedFiles\\house.size.fromBob.txt']]    

#=========make a single list from the list in a list
listOfNewfiles = [item for sublist in listOfNew for item in sublist]
# returns ['H:/New/1RecievedFiles\\cat.size.txt', 'H:/New/1RecievedFiles\\house.size.fromBob.txt']

#=========copy files
[shutil.copy2(item, CopyDir) for item in listOfNewfiles]

2 个答案:

答案 0 :(得分:3)

我设置了一个如下所示的测试目录:

$ ls -1
copyto/
car.size.txt
cat.size.txt
house.size.fromBob.txt

我相信这与你所拥有的相似。给出相同的列表,这是我如何解决您的问题:

import os, shutil
# lst not list -- naming it list overshadows a builtin
lst = ['cat size', 'house size', 'car size']
# PEP8 - lowercase with underscore here; CamelCase for classes
from_dir = os.path.abspath(os.path.expanduser('~/test'))
copy_dir = os.path.abspath(os.path.expanduser('~/test/copyto'))

to_copy = [f for f in os.listdir(from_dir) if os.path.isfile(f)]
# ['car.size.txt', 'house.size.fromBob.txt', 'cat.size.txt']

for filename in to_copy:
    needle = ' '.join(filename.split('.')[:2])
    if needle in lst:
        dest_dir = os.path.join(copy_dir, needle)
        os.mkdir(dest_dir)
        shutil.copy2(os.path.join(from_dir, filename), dest_dir)

在此之后,我的test目录完全如前所示,这是ls -R1 copyto的结果:

copyto:
car size/
cat size/
house size/

copyto/car size:
car.size.txt

copyto/cat size:
cat.size.txt

copyto/house size:
house.size.fromBob.txt

这适用于您的情况吗? (PS - Python非常适合这种事情,不是吗?)

答案 1 :(得分:0)

遍历您的列表并检查对其保存位置进行分类的术语。 I.E. 'cat','dog'或'house'

类似这样的事情

import os,shutil

for item in list:
    if 'cat' in listitem:
        shutil.copyfile(source, 'H:/new/2CopyTo/cat size/')
    elif 'house' in listitem:
        shutil.copyfile(source, 'H.......etc etc
    elif 'car'.....

这就是你想要的吗?