0

I have created a program to take inputs from user, later concatenate the data and send it to a list using append. I want to export the data from list to a .csv file, but don't know how to do it.Is there a way to do this? (Also I am using Ubuntu 20.04LTS, and VS code) Below is the list, and below that the data appended in the list :

Uploaded = []

upload =  number + " " + name + " " + str(datetime.datetime.now()) + " " + query + ":" + problem + " " + sign
Uploaded.append(upload)
rioV8
  • 12,369
  • 2
  • 12
  • 26
  • 5
    Does this answer your question? [Writing a Python list of lists to a csv file](https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file) – shimo Jun 25 '20 at 10:58

3 Answers3

1

You can try this:

from datetime import datetime
import pandas as pd

uploaded = []
number = 123
name = "Temp"
date = datetime.now()
query = 'selext * from temp;'
problem = "nothing"
uploaded.append([number, name, date, query, problem])
uploaded

uploaded List:

[[123,
  'Temp',
  datetime.datetime(2020, 6, 25, 16, 32, 5, 310469),
  'selext * from temp;',
  'nothing']]

Pandas DataFrame is the easiest way of converting list to csv

## create dataframe and save as csv    
pd.DataFrame(uploaded).to_csv("temp.csv",index=False)

Otherwise, you can use native csv python module.

Narendra Prasath
  • 1,329
  • 1
  • 8
  • 17
0

I think that this might be helpful.

Create a .csv file with values from a Python list

Kovac
  • 21
  • 4
0

You can simply implement it without any dependency:


def list_to_csv(records, columns, dst_file):
  records_csv = [','.join(map(str, r)) for r in records]
  csv_text = '\n'.join(records_csv)
  with open(dst_file, 'w') as f:
    f.write(csv_text)

records = [
  ['James', 13, 'Cat'],
  ['Karl', 20, 'Dog']
]

list_to_csv(records, columns=['name', 'age', 'pet'], dst_file='f.csv')

Also you can work with date times of any object that has the str method implemented.

Then, you can take a look at f.csv file.

Guillem
  • 1,582
  • 2
  • 11
  • 26