precious mas
precious mas

Reputation: 1

csv file loop results

I'm trying to extract csv files by the cities with `re.findall(), but when I try to do that and write to results to another csv file, it loops over and over many times!

import io
import csv
import re

lines=0
outfile1 =codecs.open('/mesh/وسطى.csv','w','utf_8')
outfile6 =codecs.open('/mesh/أخرى.csv','w','utf_8')

with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    reader = csv.reader(f)
    for row in f :
        for rows in row:
            lines += 1

            #الوسطى
            m = re.findall('\u0634\u0642\u0631\u0627\u0621',row)
            if m:
                outfile1.write(row)
            else:
                outfile6.write(row)

print("saved In to mishal !")
f.close()

I want the re.finall() cities to not loop, just execute once for each match—not loooooooping so many times whenever there's a match.

Here's a screenshot of the output showing the excessive looping:

screenshot of script's output

Upvotes: 0

Views: 69

Answers (1)

wwii
wwii

Reputation: 23743

csv readers return a list for each line of the file - your outer loop is iterating over the lines/rows and your inner loop is iterating over items in each row. It isn't clear what you want. but your conditional writes happen for each item in each row. If your intent is to check and see if there is a match in the row instead of items in the row,

for row in f :
    match = False
    for item in row:
        lines += 1    #??
        #الوسطى   
        match = re.search('\u0634\u0642\u0631\u0627\u0621',item)
    if match:
        outfile1.write(row)
    else:
        outfile6.write(row)

You could accomplish the same thing just iterating over the lines in the file without using a csv reader

with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    for line in f:
        #الوسطى
        if re.search('\u0634\u0642\u0631\u0627\u0621',line):
            outfile1.write(line)
        else:
            outfile6.write(line)

Upvotes: 1

Related Questions