How to compare a column of a csv file with an image name in python?

家住魔仙堡 提交于 2020-03-26 22:41:58

问题


I have a CSV file that lists image files with an ID number for each, like this:

21_cook.png   9
35_read.png   6
13_walk.png   2

The image files are in a folder. The code below searches out the image file names:

for dirname, dirnames, filenames in os.walk('./images'):
   for filename in filenames:
       if filename.endswith('.png'):
           names.append(filename)

This part works.

This code extracts the image names from the CSV file:

file = open('namesIma.csv')
lns = csv.reader(file)
for line in lns:
    nam = line [0]
    names1.append(nam)

How can I print the ID number of each file that's in both the images folder and the CSV file's index.


回答1:


Add a clause to your for loop over the names:

for line in lns:
    nam = line [0]
    names1.append(nam)
    if nam in names:
        print (nam, line[1])

Does that solve the problem for you?




回答2:


if nam in names: print (nam, line[1])

does not return anything also when I check:

  1. type(nam) it gives str
  2. type(names) it give list


来源:https://stackoverflow.com/questions/40557603/how-to-compare-a-column-of-a-csv-file-with-an-image-name-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!