简体   繁体   中英

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)

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.

I think that this might be helpful.

Create a.csv file with values from a Python list

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM