How to print the 2nd column of a searched string in a csv - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to print the 2nd column of a searched string in a csv (/thread-23662.html) |
How to print the 2nd column of a searched string in a csv - ptey07 - Jan-11-2020 Hi there can someone help i am trying to search for a file name in a csv (in Column A) then when it finds it print just the 2nd column (Colum B) not the whole row, this prints both the coloumns in the csv ------------------- import os f_name = os.listdir(r'C:\Users\Peter\Documents\Python test\Files')[0] print(f_name) import csv data=[] with open ("test.csv") as csvfile: reader = csv.reader(csvfile) for row in reader: data.append(row) col = [x[0] for x in data] if f_name in col: for x in range(0,len(data)): if f_name ==data[x][0]: action = print(data[x]) else: print("File not listed") RE: How to print the 2nd column of a searched string in a csv - perfringo - Jan-11-2020 Assuming that a file named 'two_columns.txt' contains space separated two columns: Then one way of getting desired result could be:look_for = ('secret.txt', 'public.txt') with open('two_columns.txt', 'r') as f: for row in f: first, second = row.split() if first in look_for: print(second) # will print: 42 123 RE: How to print the 2nd column of a searched string in a csv - ptey07 - Jan-11-2020 Thanks i will have a play, not sure tho i have of pictures and a csv the picture file name in column A and location it was taken in Column B i can get the code to look at the file name then go to the csv and search for the file name and then return the row of data, but i want it to just return the location column of that row. if u get what i mean |