How To Remove A Line From A Csv If It Contains A Certain Word?
Solution 1:
Redirect output to a new file. It will give you every line, except those that contain "external"
import sys
import re
f = open('sum.csv', "r")
lines = f.readlines()
p = re.compile('external')
for line in lines:
if(p.search(line)):
continueelse:
sys.stdout.write(line)
Solution 2:
It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file.
What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this:
csv_domain = line.split(',')[2]
But, like one of the comments said, this isn't necessarily fool proof. You are assuming none of the individual cells will have commas. Based on your example that might be a safe assumption, but in general when working with CSV files I recommend working with the Python csv module.
Solution 3:
if you can go with something else then python, grep would work like this:
grep file.csv "some regex" > newfile.csv
would give you ONLY the lines that match the regex, while:
grep -v file.csv "some regex" > newfile.csv
gives everything BUT the lines matching the regex
Post a Comment for "How To Remove A Line From A Csv If It Contains A Certain Word?"