Python add to csv file

How to Read CSV in Python, Write and Append Too

Ransomware recovery test drive: This technical workshop is designed to take you behind the scenes and shows you how to adopt strategies to automate recovery, ensuring you’re ready to become a recovery hero. REQUEST YOUR LAB

If you need to read CSV in Python like reading CSV files (and writing) to them, you’re in luck. In this tutorial, you’re going to learn how to read, write to and append data to CSV files in your Python scripts!

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • A Windows or Linux host with Python 3 installed. This tutorial will use Windows, but Linux will work fine also.
  • A code editor like VS Code to copy and paste Python code snippets to.

How to Read CSV in Python

Let’s get started and see how you can read CSV in Python. Python provides a built-in module called csv that has various methods allowing you to work with CSV files so let’s use that.

Читайте также:  Таблицы

To read CSV files, the Python csv module provides a method called reader() . Let’s first demonstrate how to use this method.

1. Create a directory at ~/pythoncsvdemo and download this csv file into it. The example CSV contains a list of fictitious people with columns of “Name,” “Sex,” “Age,” “Height (in),” and “Weight (lbs).” This CSV file will be used throughout this tutorial.

2. Next, open a code editor, paste the following Python script into it. This simple script imports the csv module and uses the reader() method to read the file and iterate over each line in the CSV file with a for loop.

import csv #import to use the csv module with open('demo_csv.csv', mode="r") as csv_file: #"r" represents the read mode reader = csv.reader(csv_file) #this is the reader object for item in reader: # you have to loop through the document to get each data print(item)

Replace the reader() method with the dictreader() method to return CSV rows in a Python dictionary rather than an array.

In the below output, you’ll see the first line is the name of the columns, with each row representing a CSV row. Each column represents an index starting from 0.

CSV output via the reader() method

CSV output via the dicteader() method

3. Perhaps you’d prefer only to see the output of one column. No problem. Provide the index number of 1 against the item variable representing the row.

import csv with open('demo_csv.csv', mode="r") as csv_file: reader = csv.reader(csv_file) for item in reader: print(item[1])# index is added to get a particular column

If you’re using the dictreader() method, replace the print() command above with print(item[«Name»]) . Since dictreader() creates a dictionary for each CSV row, you can reference columns in the row by name instead of index number.

Display list of Sexes

Creating CSV Files with Python

Using the csv module and a few handy methods, you can also write to CSV files from Python. To write a CSV file, create another script with the following code.

This script defines each column that will be in the CSV ( column_name ) along with each element in a single row ( data ). The script then opens the demo_csv1.csv for writing ( w ) and writes a single row ( writerow() ).

import csv column_name = ["Name", "Sex", "Age", "Height (in)", "Weight (lbs)"] #The name of the columns data = ['Ali',"M", 29, 71,176] #the data with open('demo_csv1.csv', 'w') as f: writer = csv.writer(f) #this is the writer object writer.writerow(column_name) # this will list out the names of the columns which are always the first entrries writer.writerow(data) #this is the data

If you need to append row(s) to a CSV file, replace the write mode ( w ) with append mode ( a ) and skip writing the column names as a row ( writer.writerow(column_name) ).

You’ll see below that Python creates a new CSV file (demo_csv1.csv), with the first row contains the column names and the second row includes the first row of data.

New CSV file created with Python

Appending to a CSV file with a Dictionary

If you’d prefer to use a dictionary, change your script slightly to use the dictwriter() method providing each field or column name as an argument ( fieldnames=field_names ), as shown below.

import csv # list of column names field_names = ['Name','Sex','Age','Height (in)','Weight (lbs)'] # Dictionary dict = with open('demo_csv.csv', 'a') as csv_file: dict_object = csv.DictWriter(csv_file, fieldnames=field_names) dict_object.writerow(dict)

Appending to a CSV file with a Dictionary

Reading from One CSV File to Write To Another

Perhaps you already have an existing CSV file and would like to use it as input to another CSV file. You can make it happen by using a combination of read mode and the reader() method and write mode and the writer() method.

  • Opens an existing file called demo_csv.csv in read mode
  • Reads the file as a CSV with the reader() method
  • Opens another CSV called new_demo_csv.csv in write mode
  • Reads each row in the source CSV file and writes those roles in the destination CSV file using the — delimiter.
import csv with open("demo_csv.csv", mode="r") as old_file: reader_obj = csv.reader(old_file) #read the current csv file with open("new_demo_csv.csv", mode="w") as new_file: writer_obj = csv.writer(new_file, delimiter="-") # Writes to the new CSV file for data in reader_obj: #loop through the read data and write each row in new_demo_csv.csv writer_obj.writerow(data)

Deleting Columns from CSV Files with Python

Let’s wrap up this tutorial by removing columns from CSV files. Unfortunately, eliminating columns isn’t as straightforward as reading or writing to CSV files, but you’ll see it still definitely possible.

To remove fields from a CSV file, you can’t directly remove them. Instead, you must read all of the fields in the CSV file and then write to another CSV file, excluding all fields you don’t want, like below.

import csv with open("demo_csv.csv", mode="r") as original: reader_obj = csv.reader(original) with open("output.csv", mode="w") as new: writer_obj = csv.writer(new) for column in reader_obj: writer_obj.writerow((column[0], column[1], column[2])) # this represents the columns you need

Conclusion

You should now have some foundational knowledge to read CSV in Python, write to CSV files, and even remove fields from CSV files. Using the Python csv module with its various methods, you can make quick work of CSV files in Python!

How do you plan to incorporate this newly discovered knowledge into your Python projects?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Источник

Python csv writer append – Python: How to append a new row to an existing csv file?

Python-How to append a new row to an existing csv file

Python csv writer append: This tutorial will help you learn how to append a new row to an existing CSV file using some CSV modules like reader/writer and the most famous DictReader/DictWriter classes. Moreover, you can also get enough knowledge on all python concepts by visiting our provided tutorials.

How to Append a new row to an existing csv file?

Python append to csv: There are multiple ways in Python by which we can append rows into the CSV file. But here we will discuss two effective methods. Before going to learn those two methods, we have to follow the standard step which is explained ahead.

The basic step to proceed in this is to have a CSV file. For instance, here we have a CSV file named students.csv having the following contents:

Id,Name,Course,City,Session 21,Mark,Python,London,Morning 22,John,Python,Tokyo,Evening 23,Sam,Python,Paris,Morning

For reading and writing CSV files python provides a CSV module. There are two different classes for writing CSV files that is writer and DictWriter.

We can append the rows in a CSV file by either of them but some solutions are better than the other. We will see it in the next section.

Append a list as a new row to an old CSV file using csv.writer()

Append csv python: A writer class is in the CSV module which writes the rows in existing CSV files.

Let’s take a list of strings:

# List of strings row_contents = [32,'Shaun','Java','Tokyo','Morning']

To add this list to an existing CSV file, we have to follow certain steps:

  • Import CSV module’s writer class.
  • Open our csv file in append mode and create a file object.
  • Pass this file object to the csv.writer(), we can get a writer class object.
  • This writer object has a function writerow(), pass the list to it and it will add the list’s contents as a new row in the associated csv file.
  • A new row is added in the csv file, now close the file object.

By following the above steps, the list will be appended as a row in the CSV file as it is a simple process.

from csv import writer def append_list_as_row(file_name, list_of_elem): # Open file in append mode with open(file_name, 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(list_of_elem)

Another Code:

Append a list as new row to an old csv file using csv.writer()

We can see that the list has been added.

Appending a row to csv with missing entries?

Python csv append: Suppose we have a list that does not contain all the values and we have to append it into the CSV file.

# A list with missing entries row_contents = [33, 'Sahil', 'Morning'] # Appending a row to csv with missing entries append_list_as_row('students.csv', row_contents)

some entries are missing in the list

output of missing files

We can see the data get appended at the wrong positions as the session got appended at the course.

csv’s writer class has no functionality to check if any of the intermediate column values are missing in the list or if they are in the correct order. It will just add the items in the list as column values of the last row in sequential order.

Therefore while adding a list as a row using csv.writer() we need to make sure that all elements are provided and are in the correct order.

If any element is missing like in the above example, then we should pass empty strings in the list like this,

row_contents = [33, ‘Sahil’, » , », ‘Morning’]

Since we have a huge amount of data in the CSV file, adding the empty strings in all of that will be a hectic task.

To save us from hectic work, the CSV provided us with the DictWriter class.

Append a dictionary as a row to an existing csv file using DictWriter in python

CSV append python: As the name suggests, we can append a dictionary as a row to an existing CSV file using DictWriter in Python. Let’s see how we can use them.

Suppose, we have a dictionary-like below,

We can see that the keys are the columns of the CSV and the values will be the ones we will provide.

To append it, we have to follow some steps given below:

  • import csv module’s DictWriter class,
  • Open our csv file in append mode and create a file object,
  • Pass the file object & a list of csv column names to the csv.DictWriter(), we can get a DictWriter class object
  • This DictWriter object has a function writerow() that accepts a dictionary. pass our dictionary to this function, it adds them as a new row in the associated csv file,
  • A new line is added in the csv file, now close the file object,

The above steps will append our dictionary as a new row in the csv. To make our life easier, we have created a separate function that performs the above steps,

from csv import DictWriter def append_dict_as_row(file_name, dict_of_elem, field_names): # Open file in append mode with open(file_name, 'a+', newline='') as write_obj: # Create a writer object from csv module dict_writer = DictWriter(write_obj, fieldnames=field_names) # Add dictionary as wor in the csv dict_writer.writerow(dict_of_elem)

Append a dictionary as a row to an existing csv file using DictWriter in python

output of appending the dict

We can see that it added the row successfully. We can also consider this thought that what if our dictionary will have any missing entries? Or the items are in a different order?

The advantage of using DictWriter is that it will automatically handle the sort of things and columns with missing entries will remain empty. Let’s check an example:

field_names = ['Id','Name','Course','City','Session'] row_dict = # Append a dict as a row in csv file append_dict_as_row('students.csv', row_dict, field_names)

column with missing entries will remain empty

We can see this module has its wonders.

Hope this article was useful and informative for you.

Источник

Оцените статью