Easy CSV
py_simple.easy_csv
easy_csv is built to simplify reading and writing CSV files.
append_row_to_csv(filepath, row, delimiter=',')
Append a single row (as a dictionary or list) to an existing CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
row
|
dict or list
|
The row data to append. |
required |
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty. |
count_csv_rows(filepath, include_header=False, delimiter=',')
Count rows in a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
include_header
|
bool
|
If True, include the header row in the count. |
False
|
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of rows in the CSV file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty. |
Example
from py_simple import count_csv_rows
row_count = count_csv_rows(filepath="people.csv")
print(row_count) # 3
import csv
with open("people.csv", "r", newline="", encoding="utf-8") as f:
row_count = sum(1 for _ in csv.reader(f)) - 1
print(row_count) # 3
delete_csv_rows(filepath, column, value, delimiter=',')
Deletes rows from a CSV file where a column matches the given value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
The path to the CSV file. |
required |
column
|
str
|
The column to check for the given value. |
required |
value
|
str
|
The value used to find rows to delete. |
required |
delimiter
|
str
|
The field delimiter. Defaults to a comma. |
','
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the CSV file does not exist. |
ValueError
|
If the file is empty, the column does not exist, or no row matches the given value. |
Example
from py_simple import delete_csv_rows
delete_csv_rows(
filepath="people.csv",
column="Name",
value="Alice"
)
import csv
import os
import tempfile
with open("people.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = list(reader)
rows = [row for row in rows if row["Name"] != "Alice"]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=reader.fieldnames)
writer.writeheader()
writer.writerows(rows)
drop_empty_csv_rows(filepath, delimiter=',')
Remove rows whose cells are all blank and rewrite the CSV in place.
The header row is always kept. A cell that contains only spaces counts as blank.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many data rows were removed. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty. |
Example
from py_simple import drop_empty_csv_rows
removed = drop_empty_csv_rows("people.csv")
print(removed) # 2
import csv
with open("people.csv", newline="", encoding="utf-8") as f:
rows = list(csv.reader(f))
header, data = rows[0], rows[1:]
kept = [row for row in data if any(cell.strip() for cell in row)]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows([header, *kept])
filter_csv_rows(filepath, column, value, return_dict=True, delimiter=',')
Filter rows where a specific column equals the given value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
column
|
str
|
Column name to filter on. |
required |
value
|
str
|
Value to match. |
required |
return_dict
|
bool
|
Whether to return dicts or lists (see read_csv_to_list). |
True
|
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[dict[str, Any]] | list[list[Any]]
|
Filtered rows (dicts or lists). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the column is not found. |
Example
from py_simple import filter_csv_rows
data = filter_csv_rows(filepath="people.csv", column="Name", value="Alice")
print(data) # [{'Name': 'Alice', 'Age': '24'}]
import csv
with open("people.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
data = [row for row in reader if row["Name"] == "Alice"]
print(data) # [{'Name': 'Alice', 'Age': '24'}]
get_csv_columns(filepath, delimiter=',')
Retrieve a CSV column names (headers) from a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
Column names. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty. |
Example
from py_simple import get_csv_columns
columns = get_csv_columns(filepath="people.csv")
print(columns) # ['Name', 'Age']
import csv
with open("people.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
columns = next(reader)
print(columns) # ['Name', 'Age']
iter_csv_rows(filepath, return_dict=True, delimiter=',')
Returns CSV rows one at a time without loading the whole file into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to a UTF-8 CSV file. |
required |
return_dict
|
bool
|
Use the first row as dictionary keys (default True). If False, yield lists including the header, like read_csv_to_list. |
True
|
delimiter
|
str
|
Field separator (default comma). |
','
|
Returns:
| Name | Type | Description |
|---|---|---|
Iterator |
None
|
Rows such as {'Name': 'Alice', 'Age': '24'}. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When iteration begins and the file does not exist. |
ValueError
|
When iteration begins and the file is empty. |
The file opens on the first iteration and closes on exhaustion. If you stop early, call the iterator's close() method to release it immediately.
Example
from py_simple.easy_csv import iter_csv_rows
for person in iter_csv_rows("people.csv"):
print(person["Name"])
import csv
with open("people.csv", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
headers = next(reader)
for row in reader:
person = dict(zip(headers, row))
print(person["Name"])
merge_csv_files(filepaths, output_filepath, delimiter=',')
Combines CSV files with matching headers into one file in input order.
Reads UTF-8 files one record at a time and writes the header only once. Header names and their order must match exactly. Header-only files are accepted; empty files or files with a blank first record are rejected. Data records are copied without changing their field count or values.
Writes to a temporary file beside the output, then replaces the output only after all inputs succeed. Inputs and any existing output are left unchanged on failure. The output must not refer to an input, including through a symbolic or hard link. An unrelated output symlink is replaced itself, leaving its target unchanged. File metadata is not copied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepaths
|
list[str]
|
Non-empty list of input paths, in merge order. |
required |
output_filepath
|
str
|
Destination path; its parent must exist. |
required |
delimiter
|
str
|
Field delimiter for all files (default is comma). |
','
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no inputs, an input has no header, headers differ, or the output refers to an input. |
OSError
|
If a file cannot be read, written or replaced. |
UnicodeError
|
If an input cannot be decoded as UTF-8. |
Error
|
If CSV parsing fails. |
Example
from py_simple import merge_csv_files
merge_csv_files(["january.csv", "february.csv"], "combined.csv")
import csv
import os
import tempfile
inputs = ["january.csv", "february.csv"]
output = "combined.csv"
if not inputs:
raise ValueError("At least one input is required")
for path in inputs:
if os.path.realpath(path) == os.path.realpath(output) or (
os.path.exists(output) and os.path.samefile(path, output)
):
raise ValueError("Output must not be an input")
temporary_path = None
try:
with tempfile.NamedTemporaryFile(
"w", newline="", encoding="utf-8", delete=False,
dir=os.path.dirname(os.path.abspath(output))
) as temporary:
temporary_path = temporary.name
writer = csv.writer(temporary)
header = None
for path in inputs:
with open(path, newline="", encoding="utf-8") as source:
reader = csv.reader(source, strict=True)
current = next(reader, None)
if not current:
raise ValueError(f"File has no header: {path}")
if header is None:
header = current
writer.writerow(header)
elif current != header:
raise ValueError(f"Headers do not match: {path}")
writer.writerows(reader)
os.replace(temporary_path, output)
finally:
if temporary_path is not None and os.path.exists(temporary_path):
os.remove(temporary_path)
read_csv_column(filepath=None, column=None, delimiter=',', *, file_path=None, column_name=None)
Read all values from a specific column in a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. Also accepts file_path as alias. |
None
|
column
|
str
|
Column name to extract. Also accepts column_name as alias. |
None
|
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
file_path
|
str
|
Keyword alias for filepath. |
None
|
column_name
|
str
|
Keyword alias for column. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
Values from the specified column. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty or if the column is not found. |
Example
from py_simple import read_csv_column
names = read_csv_column(filepath="people.csv", column="Name")
print(names) # ['Alice', 'Bob', 'Carol']
import csv
with open("people.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
names = [row["Name"] for row in reader]
print(names) # ['Alice', 'Bob', 'Carol']
read_csv_to_list(filepath, return_dict=True, delimiter=',')
Read a CSV file and return its contents Args: filepath (str): The path to the CSV file. return_dict (bool): If True, return list of dicts (keys are headers). delimiter (str): Field delimiter (default is comma).
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[dict[str, Any]] | list[list[Any]]
|
Rows as dicts (if return_dict=True) or lists. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If filepath doesn't exist. |
ValueError
|
If the file is empty. |
Example
from py_simple import read_csv_to_list
data = read_csv_to_list(filepath="people.csv")
print(data[0]) # {'Name': 'Alice', 'Age': '24'}
rows = read_csv_to_list(filepath="people.csv", return_dict=False)
print(rows[0]) # ['Alice','24']
import csv
with open("people.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
rows = list(reader)
headers = rows[0]
data = [dict(zip(headers, row)) for row in rows[1:]]
print(data[0]) # {'Name': 'Alice', 'Age': '24'}
with open("people.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
rows = list(reader)
print(rows[1]) # ['Alice', '24'] # 0 is a header row
sort_csv_by_column(filepath, column, reverse=False, output_filepath=None, delimiter=',')
Sort a CSV file based on a specific column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the CSV file. |
required |
column
|
str
|
Column name to sort by. For mixed data, values are sorted numerically first, followed by non-numeric strings and empty cells. |
required |
reverse
|
bool
|
If True, sorts in descending order. For mixed data, this reverses the grouping. |
False
|
output_filepath
|
str | None
|
Output path. If None, overwrites the source file. |
None
|
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file is empty, contains no data rows, or the column is not found. |
write_csv_from_list(filepath, data, headers=None, delimiter=',')
Write data to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Output path. |
required |
data
|
list
|
List of dicts or list of lists. |
required |
headers
|
list
|
Column names. Required if data is list of lists and you want headers. If data is dict, keys are used. |
None
|
delimiter
|
str
|
Field delimiter (default is comma). |
','
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is empty or invalid. |
Example
from py_simple import write_csv_from_list
people = [
{"Name": "Alice", "Age": "24"},
{"Name": "Bob", "Age": "31"},
]
write_csv_from_list(filepath="people.csv", data=people)
import csv
people = [
{"Name": "Alice", "Age": "24"},
{"Name": "Bob", "Age": "31"},
]
headers = list(people[0].keys())
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(people)