Skip to content

Instantly share code, notes, and snippets.

@b-mq
Last active January 13, 2025 13:11
Show Gist options
  • Save b-mq/2f116e56840bb6feff574519e000402a to your computer and use it in GitHub Desktop.
Save b-mq/2f116e56840bb6feff574519e000402a to your computer and use it in GitHub Desktop.
reverse a csv file into new _reversed file (by keeping the header row) in python
"""
This script reads a CSV file, reverses the order of its rows (except for the header),
and writes the reversed content to a new CSV file '<input_csv>_reversed'.
"""
from pathlib import Path
import sys
def app():
"""
Main application function.
Checks for correct usage and valid CSV file input.
"""
if len(sys.argv) != 2:
print("Usage: python reverse.py <input_csv>")
sys.exit(1)
elif not sys.argv[1].endswith(".csv"):
print("Please provide a valid CSV file.")
sys.exit(1)
else:
csv_file = Path(sys.argv[1])
read_reverse_write(csv_file)
print(f"Reversed CSV file: {csv_name}_reversed{csv_ext}")
def read_reverse_write(csv_file: Path) -> None:
"""
Reads the input CSV file, reverses its rows (except for the header),
and writes the reversed content to a new CSV file called <filename>_reversed.
Args:
csv_file (Path): Path to the input CSV file.
"""
csv_name, csv_ext = csv_file.stem, csv_file.suffix
with open(csv_file, mode="r") as csv, open(f"{csv_name}_reversed{csv_ext}", mode="w") as out:
lines = csv.readlines()
for l in reverse_csv(lines):
out.write(l)
def reverse_csv(csv_file: list[str]) -> list[str]:
"""
Reverses the order of rows in the CSV file, keeping the header row in place.
Args:
csv_file (list[str]): List of rows from the CSV file.
Returns:
list[str]: List of rows with the order reversed, except for the header.
"""
return [csv_file[0]] + csv_file[1:][::-1]
if __name__ == "__main__":
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment