Checking the Value of a Specific Column in Every Row of a CSV with Python
Question:
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!
Answers:
f = open('myfile.csv', 'r')
g = open('mynewfile.csv','w')
for line in f:
if int(line.split(",")[1]) != FIXED_VALUE:
g.write(line)
f.close()
g.close()
for such a simple use-case I wouldn’t use external csv libs.
*the code was not tested
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()
f = open("file.csv","r")
lines=f.readlines()
f.close()
f = open("file.csv","w")
for line in lines:
if int(line.split(",")[1]) >= 16:
f.write(line)
f.close()
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!
f = open('myfile.csv', 'r')
g = open('mynewfile.csv','w')
for line in f:
if int(line.split(",")[1]) != FIXED_VALUE:
g.write(line)
f.close()
g.close()
for such a simple use-case I wouldn’t use external csv libs.
*the code was not tested
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()
f = open("file.csv","r")
lines=f.readlines()
f.close()
f = open("file.csv","w")
for line in lines:
if int(line.split(",")[1]) >= 16:
f.write(line)
f.close()