Issue
Using data as follows for simplicity:
Name,Age,Height
Joe,14,65
Sam,18,74
Sarah,21,62
I want to go through each line of the file, compare the Age
column to some value (for example: 16). If the value is less than the fixed value, I want to delete the line.
In this example, I'd be left with the following data:
Name,Age,Height
Sam,18,74
Sarah,21,62
Thanks in advance!
Solution
Here's a basic example, using the csv module. It creates a new file less the criteria data.
#!/usr/bin/python
import csv
infile = 'input.csv'
outfile = 'output.csv'
wfh = open(outfile, 'w')
with open(infile, 'r') as fh:
reader = csv.DictReader(fh, delimiter=',')
for row in reader:
name = row['Name']
age = row['Age']
height = row['Height']
if age >= 16:
wfh.write("{},{},{}".format(name, age, height))
wfh.close()
Answered By - stevieb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.