Skip to content
Advertisement

Export filters csv data to a new csv (python)

I would like to be able to read a csv file, filter out the data that I need based on the input of a user and then take that output and write it to a new CSV file.

A manual example would be to take a table in excel, filter specific columns to a certain value and take that filtered output and move it to a new file so you only have the filtered data.

I have a csv file that I am reading in

    reader = csv.reader(data, delimiter= ',')```

I am then asking a user for input

```object1 = input('What is the first thing you need?)```
```object2 = input('What what is the second thing you need?')```

```def objs():
            values = ''
            for row in reader:
                if row[3] == object1 and row[14] == object2: 
                    values = row[0], row[1], row[3], row[7], row[14]
                    print(values)
            return values```


When I print the output of def objs I get exactly what I am looking for. However it is all one line and not separated by columns. 

How can I take this output and move it to a new .csv file with headers and so each indexed row has its own column?
  
 

Advertisement

Answer

I believe part of the problem is that the values variable doesnt hold on to anything, as in it gets overwritten after every loop. Your print statement works because it is inside the loop but the return statement will only return the values for the last loop.

def objs():
    values = '' 
    for row in reader:
        if row[3] == object1 and row[14] == object2: 
            values = [row[0], row[1], row[3], row[7], row[14]] #directly overwrites values variable
            print(values) 
    return values #this would return the last 'values' variable processed, not all of them 

Since you wanted to export them to a csv file, instead make a list that will hold lists of the values:

def objs():
    values = []
    for row in reader:
        if row[3] == object1 and row[14] == object2:
            # this will take your wanted values and add them to a list, which then gets added to values
            values.append([row[0], row[1], row[3], row[7], row[14]])
    return values

Now you can export them to csv. Full code:

reader = csv.reader(data, delimiter= ',')

object1 = input('What is the first thing you need?')
object2 = input('What what is the second thing you need?')

def objs():
    values = []
    for row in reader:
        if row[3] == object1 and row[14] == object2:
            # this will take your wanted values and add them to a list, which then gets added to values
            values.append([row[0], row[1], row[3], row[7], row[14]])
    return values

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    values = objs()
    headers = ["row0", "row1", "row3", "row7", "row14"]

    writer.writerow(headers)
    writer.writerows(values)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement