There are the following methods to convert the list to csv in Python.
- Using a built-in CSV module’s csv.writer() method.
- Using Pandas to_csv() method.
- Using numpy.savetxt() function.
Method 1: Using the inbuilt Python CSV module
Python csv module provides the csv.writer() method, which returns the write object, and then we can call the writerow() and writerows() functions to convert a list or list of lists to the csv file.
To create a file, use Python with statement, which does not require closing the file since with statement does the job for us.
import csv
cols = ["Character Name", "Series Name", "Profession", "Age"]
rows = [["Mando", "Mandalorian", "Bounty Hunter", 35],
["Grogu", "Mandalorian", "Jedi Master", 50],
["Eleven", "Stranger Things", "Kid", 14],
["Jon", "Game of Thrones", "King", 30],
["Ross", "Friends", "Paleontologist", 35]]
with open('shows.csv', 'w') as f:
# using csv.writer method from CSV package
write = csv.writer(f)
write.writerow(cols)
write.writerows(rows)
In this example, first, we have imported the csv module. Then we have defined two lists.
- rows
- columns
The cols list defines the columns of the csv file, and rows are lists that will create rows of the csv file. Use the with statement to open a shows.csv file; if it does not exist, it will make it for us and write the rows and cols to the csv file.
If you run the above code in your current directory, you will see a shows.csv file. If you open the file, you will know it is filled with comma-separated values. So this is the first way to convert a list to csv.
Method 2: Using Pandas to_csv() function
To convert the list to csv, convert from list to dataframe and then use the to_csv() function to convert the dataframe to a csv file.
import pandas as pd
char_name = ["Mando", "Grogu", "Eleven", "Jon", "Ross"]
series_name = ["Mandalorian", "Mandalorian",
"Stranger Things", "Game of Thrones", "Friends"]
profession = ["Bounty Hunter", "Jedi Master", "Kid", "King", "Paleontologist"]
age = [35, 50, 14, 30, 35]
dict = {"Character Name": char_name, "Series Name": series_name,
"Profession": profession, "Age": age}
df = pd.DataFrame(dict)
df.to_csv('shows.csv')
In this example, we first imported the pandas library, defined the four lists, and mapped it with its column using a dictionary.
Then use the pd.DataFrame() function to convert it into DataFrame and then use the to_csv() function to convert the DataFrame to a CSV file.
Method 3: Using numpy.savetxt() function
The Numpy savetxt() function saves
import numpy as np
data = [["Mando", "Grogu", "Eleven", "Jon", "Ross"],
["Mandalorian", "Mandalorian","Stranger Things", "Game of Thrones", "Friends"],
["Bounty Hunter", "Jedi Master", "Kid", "King", "Paleontologist"],
[35, 50, 14, 30, 35] ]
np.savetxt("shows.csv", data, delimiter=", ", fmt="% s")
An array to a text file. We can also use the savetxt() file to save the data into csv file.
If you run the above code, you will see the shows.csv file in your current project folder.
That is it.
Caso eu atualizar a linha com novos dados, como faço para escrever na linha de baixo e não sobrescrever?