DEV Community

Blujay0
Blujay0

Posted on • Updated on

Quick Look: Reading and Writing to CSV Files

Introduction

CSV stands for Comma Seprated Values and is a popular format for storing tabular/table-like data in a file to use. This tabular data can consist of things like financial transactions, payroll, and other statistical records of information.

Here is an example of a CSV file randomly generated from Random Data Generator opened in VSCode:

"First Name", "Last Name", "Age", "Experience (Years)", "Salary"
"Roland", "Cooper", "22", "6", "7516"
"Edith", "Reed", "19", "1", "2147"
"Aida", "Montgomery", "24", "11", "7009"
"Dominik", "Moore", "18", "6", "9427"
"Chloe", "Lloyd", "25", "6", "4715"
Enter fullscreen mode Exit fullscreen mode

The first row ALWAYS represents the column headers and the rest of the rows represent the actual data that goes into the table.

Here is a visual representation of the above CSV for you visual learners:
CSV represented as table

What We'll Be Using:

  • CSV file(s)
  • VSCode's CSV Module
  • Python

Reading the CSV File

To read our CSV file, we'll be using the reader() function provided by the CSV module. This function allows you to iterate over rows of the CSV as lists and returns an iterable reader object.

Example Code

# create a use_reader.py file in your base directory
# first you import reader from VSCode's CSV module
from csv import reader

# open() is used to open a CSV file for reading
with open("random.csv") as csvfile:

    # set csv_reader variable to the evaluated result of invoking reader(csvfile)
    csv_reader = reader(csvfile)

    print(csv_reader)

    for row in csv_reader:
        print(row)
Enter fullscreen mode Exit fullscreen mode

Terminal & Results

With the code above setup, open your terminal and run python3 use_reader.py. You should get something similar to the following result:

<_csv.reader object at 0x7f3121352120>

['First Name', 'Last Name', 'Age', 'Experience (Years)', 'Salary']
['Roland', 'Cooper', '22', '6', '7516']
['Edith', 'Reed', '19', '1', '2147']
['Aida', 'Montgomery', '24', '11', '7009']
['Dominik', 'Moore', '18', '6', '9427']
['Chloe', 'Lloyd', '25', '6', '4715']
Enter fullscreen mode Exit fullscreen mode

The first return is a representation of the iterable reader object that is returned from running the reader() function.
The second return is each element of the object that we iterated over with the for...in loop.

Writing to CSV Files

To write to CSV files, we'll be using the writer() function provided by the CSV module. This function allows you to create a writer object and create a new CSV file if needed. This can be seen as a counterpart to the reader() function. The method that is frequently used is writerow() which allows you to input a row to the CSV. The writerow() method takes in a list of values that you want to input for each row.

Example Code

# create a use_writer.py file in your base directory
# first you import writer from VSCode's CSV module
from csv import writer

# "open() is used to open a CSV file for reading"
# the "w" is declaring that this will be writing to the CSV file
with open("create_new.csv", "w") as csvfile:
    # set csv_writer variable to the evaluated result of invoking writer(csvfile)
    csv_writer = writer(csvfile)

    # pass into writerow() a list of data points you wish to write to the CSV file
    csv_writer.writerow(["First Name", "Last Name", "Age", "Experience (Years)", "Salary"])
    csv_writer.writerow(["Steven", "Spielberg", "64", "42", "60000000"])
    csv_writer.writerow(["George", "Lucas", "58", "35", "50000000"])
    csv_writer.writerow(["Christopher", "Nolan", "52", "27", "20000000"])
Enter fullscreen mode Exit fullscreen mode

Terminal & Results

With the code above setup, open your terminal and run python3 use_writer.py. You should see a new CSV file called create_new in your directory and if you examine the file, you will see the data that you created using writerow.

And that file will translate to the following table:

written CSV table

Summary

  • The reader() and writer() methods allow for easy modifications of the data in a text editor for large datasets.
  • It is a frequently-used format of data inputting and outputting because it is so widely adopted
  • Useful to know if you are working with large datasets and pickling

And that was a quick look at reading and writing to CSV files. Happy Coding!

Resources

Top comments (0)