Reputation: 185
I am trying to create a python program that tests if certain cells in a csv have the value 4, and if they do, it should write that whole row to a csv file called grade4.csv. This is the code I have so far:
import csv
with open('register-all-subs-2020-05-31.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
data = [row for row in csv.reader(csvDataFile)]
r=0
c=0
for r in range(33):
for c in range(7):
print(data[r][c])
However, I can't figure out how to go about testing certain values in the cell and writing the row to a csv. It would be great if anyone could help.
Upvotes: 0
Views: 88
Reputation: 401
Try this and modify it little bit according to your purpose :
def check_four(row):
for cell in row:
if "4" in cell:
return True
return False
def main():
with open("file.csv","r") as f:
data = f.read()
rows = data.split(",")
new_rows = []
for row in rows:
if check_four(row):
new_rows.append(row)
new_data = ','.join(new_rows)
with open("grade4.csv","w") as f:
f.write(new_data)
if __name__ == "__main__":
main()
Upvotes: 1