working on a project where I open .CSV file delete row that does not contain '80'

Viewed 66

So, my program is in python. If I have a spreadsheet in .csv format I want to delete every row that does not contain '80' and move all the remaining row's into a new .csv. I have heard pandas is very useful for this type of data manipulation but that you need certain software installed on your computer for it to run correctly? I am not sure if that is true or not but I am willing to try pandas as well.

A    B    C    D
5    11   20   6
6    1    80   11 
40   4    5    6
11   30   16   8
180  2    3    19
7    20   13   74
80   4    11   22

The Result should create a new .csv file that looks like this. Take note that If that row has number has 80 in it stays. Other wise I want it deleted. In the example, there was a row that 180 2 3 4 because there is a 80 in 180 I still wanted that whole row to stay.

A    B    C    D
6    1    80   11 
180  2    3    19
80   4    11   22

So far this is my code and I know it's NOT near complete. I am justing testing my code to see if I can copy all the rows to a new file. Like I said I want to target any row that doesn't have an 80 in it and delete it. The next part I need to do in my code is isolated all the rows with 80 and keep them. If anyone has any tutorials or resources for editing .csv that would be greatly appreciated.

import csv

outfile = open("TESTSHEET_editted.csv", 'w')  # 'w" is write mode and is the new file being created

with open('TESTSHEET.csv', 'r') as openfile: # 'r' is read mode
    reader = csv.reader(openfile, delimiter=',') # delimiter isnt necessary. It just adds a comma
    header = next(reader) #if i didnt have A B C D then this line would not be needed    
    for row in reader:  # is there any easier way to write this recursively?
        row1 = row[0]
        row2 = row[1]
        row3 = row[2]
        row4 = row[3]


        new_line = "{}, {}, {}, {}\n".format(row1, row2, row3, row4)
        outfile.write(new_line)

outfile.close()  #needs to close new created csv file for it to be used by other programs
1 Answers
import csv

b = [] #create a list to save each row of the csv
with open('TESTSHEET.csv', 'r') as openfile:
    reader = csv.reader(openfile)
    for i in reader:
        b.append(i)
b = [[str(i) for i in k] for k in b] #change all elements to strings

#check whether "80" is in the each joined element, delete the row if 80 is in 
#the row
for i,k in enumerate(b):
    if "80" in " ".join(b[i]): 
        b.pop(i)
#change all elements that is a number to int, string(A,B,C,D) remains the same
b = [[int(i) if i.isdigit() else i for i in k ] for k in b]
#write list of list to csv file
with open("TESTSHEET_Edited.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(b)
Related