Soumya Goal
Soumya Goal

Reputation: 3

Is there a way to export python list to a csv file?

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)

Upvotes: 0

Views: 511

Answers (3)

Narendra Prasath
Narendra Prasath

Reputation: 1531

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.

Upvotes: 1

Guillem
Guillem

Reputation: 2647

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.

Upvotes: 0

Kovac
Kovac

Reputation: 21

I think that this might be helpful.

Create a .csv file with values from a Python list

Upvotes: 0

Related Questions