Write list to csv file python

3 Easy Ways to Convert Python List to CSV File

Method 1: 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.

Example

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 =  "Profession": profession, "Age": age> df = pd.DataFrame(dict) df.to_csv('shows.csv')

Method 2: Using the inbuilt Python CSV module

Python csv module provides the csv.writer() method that 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.

Example

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) 

Method 3: Using numpy.savetxt() function

Numpy savetxt() method is “used to save an array to a text file.”

Example

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.

1 thought on “3 Easy Ways to Convert Python List to CSV File”

Caso eu atualizar a linha com novos dados, como faço para escrever na linha de baixo e não sobrescrever? Reply

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Write List to CSV in Python

Write List to CSV in Python

  1. Write List to CSV in Python Using the csv.writer() Method
  2. Write List to CSV in Python Using the Quotes Method
  3. Write List to CSV in Python Using the pandas Method
  4. Write List to CSV in Python Using the NumPy Method

A CSV file can store the data in a tabular format. This data is a simple text; every row of data is called the record, and each one can be separated with commas.

This article will discuss the different methods to write a list to CSV in Python.

Write List to CSV in Python Using the csv.writer() Method

Let’s first import the csv module:

Suppose we take the following entries to write into a CSV file.

RollNo,Name,Subject 1,ABC,Economics 2,TUV,Arts 3,XYZ,Python 

Now, the complete example code is as follows:

import csv  with open('students.csv', 'w', newline='') as student_file:  writer = csv.writer(student_file)  writer.writerow(["RollNo", "Name", "Subject"])  writer.writerow([1, "ABC", "Economics"])  writer.writerow([2, "TUV", "Arts"])  writer.writerow([3, "XYZ", "Python"]) 

If you run the above codes, the students.csv file will be created, row-wise, in the current directory with the entries that are present in the code. The csv.writer() function will create the writer() object, and the writer.writerow() command will insert the entries row-wise into the CSV file.

Write List to CSV in Python Using the Quotes Method

In this method, we will see how we can write values in CSV file with quotes. The complete example code is as follows:

import csv list = [["RN", "Name", "GRADES"],  [1, 'ABC', 'A'],  [2, 'TUV', 'B'],  [3, 'XYZ', 'C']] with open('studentgrades.csv', 'w', newline='') as file:  writer = csv.writer(file, quoting=csv.QUOTE_ALL,delimiter=';')  writer.writerows(list) 

The studentgrades.csv file will be created in the current directory. The csv.QUOTE_ALL() function places double quotes on all the entries, using a delimiter ; for separation.

RN;"Name";"GRADES" 1;"ABC";"A" 2;"TUV";"B" 3;"XYZ";"C" 

Write List to CSV in Python Using the pandas Method

This method uses the Pandas library, which holds a complete DataFrame. If you do not have this library installed on your PC, you can use an online tool called Google Colab.

The complete example code is as follows:

import pandas as pd name = ["ABC", "TUV", "XYZ", "PQR"] degree = ["BBA", "MBA", "BSC", "MSC"] score = [98, 90, 88, 95] dict = 'name': name, 'degree': degree, 'score': score> df = pd.DataFrame(dict) df.to_csv('test.csv') 
 name degree score 0 ABC BBA 98 1 TUV MBA 90 2 XYZ BSC 88 3 PQR MSC 95 

This method writes the Python list into a CSV file as a DataFrame.

Write List to CSV in Python Using the NumPy Method

This method uses the NumPy library to save a list to a CSV file in Python. The complete example code is as follows:

import numpy as np list_rows = [ ['ABC', 'COE', '2', '9.0'],['TUV', 'COE', '2', '9.1'], ['XYZ', 'IT', '2', '9.3'],['PQR', 'SE', '1', '9.5']] np.savetxt("numpy_test.csv", list_rows, delimiter =",",fmt ='% s') 

The savetxt() function of the NumPy library will write a CSV file from the Python list.

ABC COE 2 9 TUV COE 2 9.1 XYZ IT 2 9.3 PQR SE 1 9.5 

Related Article — Python CSV

Related Article — Python List

Copyright © 2023. All right reserved

Источник

How to write a list to CSV in Python

In this Python tutorial, we will learn the Python write list to CSV. I will show 2 different examples explaining, how to write a list to a CSV file in Python.

Python write a list to CSV

Here, we can see how to write a list to CSV in Python.

  • In this example, I have imported a module called csv and declared a variable as details.
  • And another variable called rows as rows = [ [‘sushma’, ‘2nd’, ‘2023’, ‘Physics’], [‘john’, ‘3rd’, ‘2022’, ‘M2’], [‘kushi’, ‘4th’, ‘2021’, ‘M4’]] and then to open the csv file, I have used with open(‘student.csv’, ‘w’) as f: is used to open the file.
  • The student.csv is the name of the file, the “w” mode is used to write the file, to write the list to the CSV file write = csv.writer(f), to write each row of the list to csv file writer.writerow() is used.
import csv Details = ['Name', 'class', 'passoutYear', 'subject'] rows = [ ['sushma', '2nd', '2023', 'Physics'], ['john', '3rd', '2022', 'M2'], ['kushi', '4th', '2021', 'M4']] with open('student.csv', 'w') as f: write = csv.writer(f) write.writerow(Details) write.writerows(rows) 

You can see the list as the output in the below screenshot.

Python write a list to CSV

Let us check another example.

Write a list to CSV in Python

Python has built-in support for writing to and reading from CSV files through its CSV module. Here is a step-by-step guide on how to write a list to a CSV file.

Step 1: Create Your List

First, create a list or lists that you want to write to a CSV file in Python.

# Example list data = ['apple', 'banana', 'cherry'] # Example list of lists (represents rows and columns) data_matrix = [ ['Name', 'Age', 'Country'], ['Alice', 30, 'USA'], ['Bob', 28, 'Canada'], ['Charlie', 35, 'UK'] ] 

Step 2: Write List to CSV

Now, let’s write the list to a CSV file using the csv module.

Example 1: Writing a Single List

In this example, the data list will be written to a CSV file where each element is in a new row.

import csv data = ['apple', 'banana', 'cherry'] # Open file to write data with open('fruits.csv', 'w', newline='') as file: writer = csv.writer(file) # Write each item in a new row for item in data: writer.writerow([item]) 

Example 2: Writing a List of Lists (Matrix)

In this example, the data_matrix list will be written to a CSV file where each inner list represents a row.

import csv data_matrix = [ ['Name', 'Age', 'Country'], ['Alice', 30, 'USA'], ['Bob', 28, 'Canada'], ['Charlie', 35, 'UK'] ] # Open file to write data with open('people.csv', 'w', newline='') as file: writer = csv.writer(file) # Write each inner list as a new row writer.writerows(data_matrix) 
  • In the open() function, the ‘w’ parameter specifies that the file should be opened in write mode.
  • The newline=” parameter in the open() function ensures that newlines are handled properly on all platforms.
  • The writerow() method writes a single row to the CSV file. It takes an iterable (like a list) as an argument.
  • The writerows() method writes multiple rows at once. It takes a list of iterables.

This is how to write lists to CSV files in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Читайте также:  What is boolean expression in java
Оцените статью