Generate a CSV object without a file (in python)

59 Views Asked by At

So, I need to generate a CSV object just to POST it to an API (part of the script). I would prefer to avoid saving the file in the server storage (even if it's a temp file) before sending it in the request.

So far, I found the CSV file to upload is a <_io.TextIOWrapper name='file.csv' mode='r' encoding='cp1252'> type, but not sure how to generate it from a list of lists.

[
    ['HEADER1', HEADER2],
    ['value1', 'value2],
    ....
]

Any idea is appreciated!

1

There are 1 best solutions below

0
On
import csv
import io
import requests

data = [
    ['HEADER1', 'HEADER2'],
    ['value1', 'value2'],
    # Add more rows as needed
]

# Create a BytesIO object
csv_file = io.StringIO()

# Use the csv.writer to write the list to the BytesIO object
csv_writer = csv.writer(csv_file)
csv_writer.writerows(data)

# Post the BytesIO object in a Python request
url = 'https://example.com/upload'
files = {'file': ('data.csv', csv_file.getvalue())}
response = requests.post(url, files=files)