Create a .CSV File with Values from a Python List

Create a .csv file with values from a Python list

import csv

with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)

Edit: this only works with python 2.x.

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)

exporting list into a csv file using python

You need to convert the list object into csv object.

import csv

with open('MyList.csv', 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(MyList)

Refer the following question by Fortilan
Create a .csv file with values from a Python list

How to save a list as a CSV file with new lines?

use pandas to_csv (http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html)

>>> import pandas as pd
>>> df = pd.DataFrame(some_list, columns=["colummn"])
>>> df.to_csv('list.csv', index=False)

Writing a Python list of lists to a csv file

Python's built-in CSV module can handle this easily:

import csv

with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

Update for Python 3

import csv

with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)

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

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.

Want to create a key value pair list from csv file but unable to

In addition to @Andrew's answer, try pprint to output the exact format as what you wanted.

import pprint

# ...
# ...
for row in reading_file:
if row[2] == postcode:
output.append((row[1], row[4]))

print("suburb, values")
pprint.pprint(output)

Output

suburb, values
[('Adelaide', 'Small_Animal'),
('Adelaide', 'Oncology'),
('Adelaide', 'Surgery'),
('Adelaide', 'Annual_Checkup'),
('Adelaide', 'Wildlife')]

Or, if you want the output to be table-like, try using formatted string literals/ f-strings.

# ...
# ...
sub_width = val_width = 0
for row in reading_file:
if row[2] == postcode:
output.append((row[1], row[4]))

# calculate the minimum width of each column
sub_width = len(row[1]) if len(row[1]) > sub_width else sub_width
val_width = len(row[4]) if len(row[4]) > val_width else val_width

print(f"+{'='*(sub_width+2)}+{'='*(val_width+2)}+")
print(f"| {'Suburb':{sub_width}} | {'Service':{val_width}} |")
print(f"+{'='*(sub_width+2)}+{'='*(val_width+2)}+")
for row in output:
print(f"| {row[0]:{sub_width}} | {row[1]:{val_width}} |")
print(f"+{'-'*(sub_width+2)}+{'-'*(val_width+2)}+")

Output

+==========+================+
| Suburb | Service |
+==========+================+
| Adelaide | Small_Animal |
+----------+----------------+
| Adelaide | Oncology |
+----------+----------------+
| Adelaide | Surgery |
+----------+----------------+
| Adelaide | Annual_Checkup |
+----------+----------------+
| Adelaide | Wildlife |
+----------+----------------+

Alternatively, the output can also be fed to a template and returned as HTML table. You can pass any data you need to the template as template variables. You can name the variables whatever you want, as long as the template uses the same variable names.

template(filepath, var1=data1, var2=data2, ...)

Assume you have the following project structure

project-name
|-- views
| |-- index.tpl
| ...
|-- main.py

Revise your Python script

# ...
# ...
for row in reading_file:
if row[2] == postcode:
output.append((row[1], row[4]))

return template('views/index.tpl', title="Available Vet Service", header=["Suburb", "Values"], rows=output)

Content of index.tpl

<html lang="en">
<head>
<meta charset="utf-8">
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous"
>
<title>{{title}}</title>
</head>
<body>
<div>
<table class="table table-striped table-hover table-responsive-sm">
<thead class="thead-dark">
<tr>
% for col_title in header:
<th scope="col">{{col_title}}</th>
% end
</tr>
</thead>
<tbody>
% for cell in rows:
<tr>
<td>{{cell[0]}}</td>
<td>{{cell[1]}}</td>
</tr>
% end
</tbody>
</table>
</div>
</body>
</html>

Here's the screenshot of the HTML output.

Output as HTML Table

Python - how to loop through unique values in column, create dataframe and output to csv for each one

You never rename save_as in the loop. Try this:

for Acct in acctlist:
save_as = Acct + ".csv"
Acct_df = (data_df[data_df["Acct"] == Acct])
Acct_df.to_csv(save_to + save_as)

Note that looping over a pandas dataframe is generally a bad idea as it is inefficient. It might work fine in this case especially with a small dataframe but in general you should try to avoid it.

You can accomplish this same task using apply:

import os
data_df.groupby('Acct').apply(
lambda group: pd.DataFrame.to_csv(group, os.path.join(save_to, f'{group.name}.csv'))
)


Related Topics



Leave a reply



Submit