Harshan Gowda Harshan Gowda - 2 months ago 15
Python Question

How to read columns from CSV file in Python

def rowfilter():
field_data = {}
try:
csv_read = csv.reader(open('sample.csv', ), delimiter=',', quotechar='|')
for row in csv_read:
for field in row[7]:
print(field)


except FileNotFoundError:
print("File not found")

rowfilter()


This code runs successfully but I want this code to print data prior to the user_input.
e.g. if user enter 5 then its should print all the details from 1 to 5, along with all the column associated with it.

Answer
def rowfilter(col1, col2):

    try:
        csv_read = csv.reader(open('items.csv'), delimiter=',', quotechar='|')
        for row in csv_read:
        print(row[int(cols[0]):int(cols[1])])  

    except FileNotFoundError:
            print("File not found")

inputrows = input("Enter columns in the format: col1 col2 ")
rowfilter(inputrows.split()))

I have edited this answer as per your comment, it is possible to treat the csv row as a list once the csv reader has read it. Therefore this method will print columns from col1 to col2. Note that python is 0 indexed.

Comments