How to update my same csv file and use it for matching in python?
Question: There 2 csv files.My first task is to match the contents of both the files
with a specified keyword and create a new file with the keyword contents and
named as keyword.csv.It is working fine. Problem part:I want to use the
remaining.csv again and again to remove those values which are being matched
by the keywords. program is not throwing any errors but not writing all the
content in the csv properly.

    
    
    import csv
    
    handle2 =''
    each=''
    row=''
    cat_var=''
    handle1=''
    with open('ss.csv') as handle2:
        for each in handle2:
            strng_conv = ''.join(map(str,each.rstrip('\n')))
            print strng_conv
            file_name = strng_conv+'.csv'
            print file_name
            cat_file = open(file_name,'wb')
            cat_var = csv.writer(cat_file,delimiter=' ')
            with open('repaired.csv', 'r') as csvfile:
                handle1 = csv.reader(csvfile, delimiter=' ')
                for row in handle1:
                    if each.rstrip() in row:
                        cat_var.writerow(row)
                        csvfile.close()
    
                    else:
                        with open('repaired.csv','w') as csvfile:
                            handle1 = csv.writer(csvfile,delimiter=' ')
                            handle1.writerow(row)
                    csvfile.close()
    
    
            cat_file.close()
    
    csvfile.close()
    handle2.close()
    

**ss.csv contains items like**

    
    
    yepme
    reebok
    adidas
    baggit
    

**repaired.csv contains**

    
    
    Waybill Contents    Amount  COD Amount  Type
    928049  123456  yepme bag   1109    0   Pre-paid
    904096  15116916453 yepme polish    518 0   Pre-paid
    922222  52255       puma   abc     522  cod
    

suppose if it matches yepme contents I want repaired.csv shpuld have only row
having puma meaning all the leftovers after a match

**sample output files to be created like this-These file contains all the
matched data**

    
    
    yepme.csv
    reebok.csv
    adidas.csv
    

**Repaired.csv at the end should contain those rows which are not matched in
any of the keywords** like I haven't put puma for match so only remaining
entry should be of puma left in the repaired.csv


Answer: The problem you have is that you don't fully understand how the IO is working
here;

When you do `with X...` what is actually happening under the hood is python
calls the `__enter__` method of the object, and then when the scope is left
(i.e. the indent level of the `with` statement), it calls the `__exit__`
object of the same object.

The following two snippets are equivalent*:

    
    
    with open("file1", "r") as a:
      ...
    

and

    
    
    tmp = open("file1", "r")
    a = tmp.__enter__()
    
    ...
    
    a.__exit__()
    

(* That is, if you ignore exceptions being chucked out and stuff )

For `File` objects, the `__exit__()` will clean up by closing the file and
whatnot - i.e. you shouldn't be closing the file after a `with open(...) as
X:`.

And the second thing you're doing, which is perhaps iffy and might not get you
the results you desire:

You're looping over the contents of a file, while editing the same file (or
maybe at least you think you do). And you're reading the files a couple of
different ways.

when you do `for line in file_object` ititerates through the file, moving an
internal pointer.

When you open the file, and then read it in using some special reader, you're
creating a new object - which will be independent from the actual file. Mixing
all of these different methods is likely going to give you results which
inconsistent and confusing, and a headache to debug when you make assumptions
about how they work.

It will probably be much easier and clearer to just read in the two original
files, and then parse them as python objects, rather than opening and closing
all of these files. I'll update this if you alter your question so it's a
little clearer what you want to do.

try something like this:

    
    
    keywords = []
    with open("ss.csv", "r") as keywords_file:
      for line in keywords_file:
        keywords.append(line.strip())
    
    
    outputs = {}
    left_overs= []
    with open("remaining.csv", "r") as remaining_file:
      for line in remaining_file:
    
        for keyword in keywords:
          if keyword in line:
            if keyword in outputs:
              outputs[keyword].append(line)
            else:
              outputs[keyword] = [line]
            break
        else:
          left_overs.append(line)
    
    for keyword, output in outputs.items():
      with open(keyword + ".csv", "w") as output_file:
        for line in output:
          output_file.write(line)
    
    with open("remaining.csv", "w") as remaining_file:
      for line in left_overs:
        remaining_file.write(line)
    

Does that do what you're aiming for?

