将png移动到python中的相应文件夹

时间:2017-08-31 20:14:50

标签: python csv

我有一个包含两列目录文件名的csv。 csv中的每一行显示每个文件所属的目录,如此

Directory, File Name

DIR18, IMG_42.png

DIR12, IMG_16.png

DIR4, IMG_65.png

到目前为止,我已经编写了代码,用于从csv中获取每个目录和文件名,然后在目标中获取所有文件,如下所示:

movePng.py

import shutil
import os
import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('/User/Results.csv') as f:
    reader = csv.DictReader(f)
    for row in reader: 
        for (k,v) in row.items(): 
            columns[k].append(v) 

source = '/User/PNGItems'

files = os.listdir(source)

for f in files:
    pngName = f[:-4]
    for filename in columns['File Name']:
        fileName = filename[:-4]
        if pngName == fileName
            # GET THIS POSITION IN columns['File Name'] for columns['Directory']
            shutil.move(f, source + '/' + DIRECTORY)
  

如何获取列['文件名']的索引并从列['目录']中获取相应的目录?

2 个答案:

答案 0 :(得分:1)

您应该将分配读入字典,然后查询:

folder_assignment_file = "folders.csv"

file_folder = dict()
with open(folder_assignment_file, "r") as fh:
    reader = csv.reader(fh)
    for folder, filename in reader:
        file_folder[filename] = folder

然后获取目标文件夹:DIRECTORY = file_folder[fileName]

其他一些提示:

  • filenamefileName不是好的变量名,这只会导致很难找到错误,因为Python区分大小写
  • 使用os.path.splitext拆分文件名
  • 如果不是所有文件都在一个文件夹中,glob模块和os.walk可能派上用场

修改

创建dict可以做得更好:

with open(folder_assignment_file, "r") as fh:
    reader = csv.reader(fh)
    file_folders = {filename: folder for folder, filename in reader}

答案 1 :(得分:0)

为了解决这个问题,我使用了@Peter Wood的建议并且效果很好。我还得修改shutil。

以下是代码

for f in files:
    pngName = f[:-4]
    for filename, directory in zip(columns['File Name'], columns['Directory']):
        fileName = filename[:-4]
        if pngName == fileName:
            directoryName = directory[1:]
            shutil.move(os.path.join(source, f), source + '/' + directoryName)