问题
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:
- type(nam) it gives str
- 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