0

I am working on a simple program to open a file and read certain rows and then print them in another new file but I want to cut them and remove them from the earlier csv. how do I do that?. This is what I have tried.

import csv

f = open('1.csv')
csv_f = csv.reader(f)

content_value = []

for row in csv_f:
    if 'yepme' in row[2]:
        content_value.append(row)


g = open('output.csv', 'wb')

wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)

I am editing and found the answer:

import csv

f = open('1.csv')
csv_f = csv.reader(f)

content_value = []
old_value = []
for row in csv_f:
    if 'yepme' in row[2]:
        content_value.append(row)
    else:
        old_value.append(row)

g = open('output.csv', 'wb')

wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)

h = open('2.csv','wb')

ws = csv.writer(h, dialect='excel')
ws.writerows(old_value)
Joannah Nanjekye
  • 429
  • 1
  • 5
  • 16
  • Can you add an example of the csv in input? I think that it's not parsed correctly because the reader function lacks some parameters: delimiter=' ', quotechar='|' – Thomas8 Feb 09 '15 at 07:17
  • suppose I am matching for the keyword yepme and its picking up and copying to the output file but its only copying I want the extracted rows to be removed from the 1.csv – Nikhil Parmar Feb 09 '15 at 07:19
  • Ok, but the csv is for example aaa,bbb,ccc or "aaa";"bbb";"vvv"? – Thomas8 Feb 09 '15 at 07:21
  • 1
    a simple way would be to overwrite the input file, if 'yepme' output else input – Thiru Feb 09 '15 at 07:26
  • Better use `with open(...) as f:`, since otherwise the files remain open (that is why you had to chose another name in your edited answer). See the end of chapter 7.2.1 here: https://docs.python.org/3.4/tutorial/inputoutput.html – Sebastian Werk Feb 09 '15 at 08:41

1 Answers1

2

A similar problem is mentioned in this question.

Short solution: Write two files: One with the extracted lines, one with the leftovers.

Coded solution:

import csv

with open('1.csv', 'r') as f:
    csv_f = csv.reader(f)

new_content = []
old_content = []

for row in csv_f:
    if 'yepme' in row[2]:
        new_content.append(row)
    else:
        old_content.append(row)

with open('output.csv', 'wb') as f:
    wr = csv.writer(f, dialect='excel')
    wr.writerows(new_content)

with open('1.csv', 'wb') as f:
    wr = csv.writer(f, dialect='excel')
    f.writerows(old_content)

I never used csv, but you should get the idea. If your csv-file is very huge, you should probably read and write line-by-line to avoid memory issues.

Community
  • 1
  • 1
Sebastian Werk
  • 1,568
  • 2
  • 17
  • 30