使用python将图像排序(使用json)到文件夹

时间:2019-04-03 06:09:14

标签: python json image sorting

我有一大堆图像(在一个文件夹中),并使用软件标记了它们。输出是一个包含标签的json文件。我想编写一个脚本,该脚本应能够根据json文件上的描述标签创建文件夹并移动图像。到目前为止,我已经用python访问json文件并显示所需的标签。

CODE1:

import json
import os
with open('filedirectory.json') as json_data:
    data = json.load(json_data)
for i, r in enumerate(data):
     if r['label'] != 'tag' 
            print(i)
            print(r['label']['tag1'])

CODE2:

import json
import os
import shutil
path = "filedirectory//samplefolder"
try:  
    os.mkdir(path)
except OSError:  
    print ("Creation of the directory %s failed" % path)
else:  
    print ("Successfully created the directory %s " % path)
source = "filedirectory//images"
dest1 = "filedrectory//tag1"
dest1 = "filedrectory//tag2"
files = os.listdir(source)
with open('filedirectory.json') as json_data:
    data = json.load(json_data)
    for i, r in enumerate(data):
        if r['label']['tag1'] = 'tag1' 
            shutil.move(f, tag1)

第一个代码显示标签输出。 第二个代码是我想尝试的代码,但不确定是否可以运行。有帮助吗?

1 个答案:

答案 0 :(得分:0)

我看到CODE2有以下问题:

是:if r['label']['tag1'] = 'tag1' 应该是:if r['label']['tag1'] == 'tag1'

在以下行中:shutil.move(f, tag1)您正在使用ftag1,但是tag1没有更早定义,f没有更早定义。

我不知道是否还有其他问题,但是如果您担心它会使您的文件混乱,我建议您按以下方式创建函数(在CODE2开头):

def mock_move(a,b):
    print('moving from:',a,'to',b)

然后用shutil.move替换mock_move并启动您的CODE2,这样您就可以检查它是否在做应做的事情而不会移动文件。确定可以正常工作后,可以将mock_move替换为shutil.move并启动CODE2。