Search code examples
pandasopencsv

read the csv file with pandas


file_contents = file.stream.read().decode("utf-8")

I have just started reading the csv file through postman. I want to get the data and add it to the database. I am getting the output in string format. I want the file uploaded to be as csv file.


Solution

  • This is the basic template. I don't have much info or input from your side so I can't test it myself. But this is how I did in one of my project. So free to modify the code.

    To download as csv:

    def get_table_download_link(df):
        """Generates a link allowing the data in a given panda dataframe to be downloaded
        in:  dataframe
        out: href string
        """
        csv = df.to_csv(index=False)
        b64 = base64.b64encode(csv.encode()).decode()  # some strings <-> bytes conversions necessary here
        href = f'<a href="data:file/csv;base64,{b64}">Download csv file</a>'
    

    To upload as CSV:

    decoded = base64.b64decode(content_string)
    df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))