Search code examples
pythoncsvexport-to-csv

PY - How to extract data from CSV and pasted to other CSV


I was assigned a task to take a data from a CSV file which is an export from a biometric function. What I need to do is to take that data and past it into another CSV file that is sent to the client.

So far I was able with this code to read the file and create the file that needs to be sent, but I'm unable to paste the data to it.

import csv

with open('clock_in.csv', "wt") as fp:
    writer = csv.writer(fp, delimiter=".")
    writer.writerows(['data'])

with open ("clock-in.csv", ) as fp:
    reader = csv.reader(fp, delimiter=",", quotechar='"')
    data_read = [row for row in reader]
        
    print(data_read)

Regarding the headers and such pretty much are:

['Data']

['NO'], ['Last_Name'], ['First_Name'], ['Date'], ['Time'], ['Status']

Any ideas on how to do extract the data from the file A and then paste it to file B? Another issue is that I haven't being able to figure out how to skip the rows that on the status column are equal to False.

I have tried multiple public answer and yet nothing seems to work, I tried with pandas and it didn't work. It gave me an error message. The closest that I've been to successfully complete the task is this where the program is able to read the code but not able to copy the data and add to the other file because haha I don't know, sorry.


Solution

  • Assuming that the cutting and pasting part isn't a necessary part of the process that you have to keep for some reason, this should work:

    import pandas as pd 
    file=pd.read_csv('clock_in.csv') #extract what's in the file
    data=file[file.Status!='False'] #filter out the rows you don't want, where Status is False
    data.to_csv("clock-in.csv", index=False) #load into a different .csv and give it a slightly different file name
    

    It looks like the problem is that you are trying to write the file before you read it - read in the data first, then do any transformations, then write to the filename of your choice. Although you can select specific columns, as far as I know you can't transform the data (AKA filter out the False values in the Status column) as you are reading it in.