Home » 10 Useful Python One-Liners for CSV Processing

10 Useful Python One-Liners for CSV Processing

by
3 minutes read

In the realm of data manipulation, CSV files reign supreme. These comma-separated values store vast amounts of information in a simple, human-readable format. When it comes to processing these files efficiently, Python stands out as a go-to language for its versatility and concise syntax. Harnessing the power of Python one-liners can streamline your CSV processing tasks, making operations faster and code cleaner. Let’s explore ten useful Python one-liners that can turbocharge your CSV workflows.

  • Read a CSV File:

“`python

import csv

data = list(csv.reader(open(‘data.csv’)))

“`

Reading a CSV file in one line is a breeze with Python’s `csv` module. This one-liner reads the contents of ‘data.csv’ into a list, ready for further processing.

  • Write to a CSV File:

“`python

import csv

data = [[‘Alice’, 24], [‘Bob’, 30], [‘Charlie’, 28]]

csv.writer(open(‘output.csv’, ‘w’)).writerows(data)

“`

To write data to a CSV file, use this one-liner to quickly dump the contents of a list of lists into ‘output.csv’.

  • Filter Rows Based on a Condition:

“`python

import csv

data = [row for row in csv.reader(open(‘data.csv’)) if row[2] == ‘Engineer’]

“`

This one-liner filters rows in a CSV file based on a specific condition, such as selecting only those rows where the third column contains ‘Engineer’.

  • Calculate Column Sum:

“`python

import csv

total = sum(int(row[1]) for row in csv.reader(open(‘data.csv’)))

“`

Need to find the sum of values in a specific column? This one-liner does the trick by summing up the values in the second column of ‘data.csv’.

  • Find Unique Values in a Column:

“`python

import csv

unique_names = set(row[0] for row in csv.reader(open(‘data.csv’)))

“`

To extract unique values from a column, this one-liner uses a set comprehension to store only unique entries from the first column of ‘data.csv’.

  • Sort CSV Data by Column:

“`python

import csv

sorted_data = sorted(csv.reader(open(‘data.csv’)), key=lambda x: int(x[1]))

“`

Sorting CSV data based on a specific column is a cinch with this one-liner. Here, the data is sorted by the values in the second column.

  • Calculate Column Average:

“`python

import csv

avg = sum(int(row[1]) for row in csv.reader(open(‘data.csv’))) / len(data)

“`

Easily calculate the average of values in a column using this one-liner. It sums up the values in the second column of ‘data.csv’ and divides by the total number of rows.

  • Merge Two CSV Files:

“`python

import csv

data1 = list(csv.reader(open(‘data1.csv’)))

data2 = list(csv.reader(open(‘data2.csv’)))

merged_data = data1 + data2

“`

Combining data from two CSV files is straightforward with this one-liner. It reads the contents of both files into lists and merges them together.

  • Extract Specific Columns:

“`python

import csv

selected_data = [[row[0], row[2]] for row in csv.reader(open(‘data.csv’))]

“`

When you only need certain columns from a CSV file, this one-liner extracts the first and third columns into a new list.

  • Count Rows in a CSV File:

“`python

import csv

num_rows = sum(1 for row in csv.reader(open(‘data.csv’)))

“`

To quickly count the number of rows in a CSV file, use this one-liner. It counts the total rows by iterating through the file.

Boost your CSV processing capabilities with these Python one-liners. Whether you’re reading, writing, filtering, or analyzing CSV files, these concise lines of code pack a punch, helping you work smarter and faster. Next time you find yourself knee-deep in CSV operations, remember these handy Python tricks to streamline your workflow effortlessly. Working with CSVs has never been more efficient!

You may also like