Home > Back-end >  Extract line by line from csv python
Extract line by line from csv python

Time:08-10

i have a csv file and i want to extract every single line and save it in different files. For exemple i extract the line 1 and save it to line1.txt then the line 2 and save it to line2.txt ... This is my code

with open('output.csv', 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        for row in csv_dict_reader:
            print(row['DOC_TYPE'],row['EXTRACTED_TEXT']) 

i tried to use this function but his is only for the first line

headers=next(file_data)

i tried to use this but it didn't work

print(row['EXTRACTED_TEXT'][0])

Can you help me ?

CodePudding user response:

Something like this?

with open('output.csv', 'r') as read_obj:
    for fname, line in enumerate(read_obj):
        with open(f"line{fname}.txt") as write_obj:
            write_obj.write(line)

CodePudding user response:

In this line DictReader(read_obj)

I think it should be csv.DictReader(read_obj) . Also depending on your experience are you using "import csv" at the start?

Edit on comment:

A=[]
for row in csv_dict_reader:
    A.append(row)
#now rows are elements of this list. 
#For printing 3rd line 
print(A[2])
  • Related