[Python] New line added to file when writing from StringIO

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    I have a piece of code that writes a csv response to a StringIO() object. I return this object through and endpoint and also use this output to generate a csv file that will be stored on the server.

    @app.post('/csv-data')
    def get_csv(data: DataRequest):
    if not data.headers:
    raise HTTPException(status_code=400, detail="Headers cannot be empty")
    if data.number_of_records <= 0:
    raise HTTPException(status_code=400, detail="Number of requested records must be more than 0")

    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    file_name = f"data_{timestamp}.csv"
    file_path = os.path.join(STORAGE_DIR, file_name)

    headers = [
    {"name": header.name, "description": header.description, "sample_data": header.sample_data}
    for header in data.headers
    ]
    response = open_ai_interface.generate_data(headers, data.number_of_records)

    output = StringIO()
    csvwriter = csv.writer(output, quoting=csv.QUOTE_MINIMAL)
    for row in response:
    csvwriter.writerow(row.split(','))


    output.seek(0)
    with open(file_path, 'w') as f:
    f.write(output.getvalue())

    output.seek(0)
    return StreamingResponse(output, media_type="text/csv", headers={"Content-Disposition": f"attachment; filename={file_name}"})


    The issue I'm facing is that the generated .csv file contains an extra line between each record. When I send a request through the browser or Postman I get the response with now new lines between records. This leads me to assume that there could be a better way to write the csv data to a file. I would appreciate suggestions

    Continue reading...

Compartilhe esta Página