-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcsvcolumn.py
66 lines (57 loc) · 1.77 KB
/
csvcolumn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# file: csvcolumn.py
# vim:fileencoding=utf-8:ft=python
#
# Copyright © 2016-2018 R.F. Smith <[email protected]>.
# SPDX-License-Identifier: MIT
# Created: 2016-03-19T13:03:26+01:00
# Last modified: 2020-12-16T00:24:54+0100
"""Prints a single column from a CSV file."""
import csv
import sys
import argparse
__version__ = "2020.12.16"
def getdata(fn, colnum, delim=";"):
"""
Read a column of data from a CSV file.
Arguments:
fn: Path of the file to read.
colnum: Index of the column to read.
delim: Delimiter to use (defaults to ';').
Returs:
A list of extracted data.
"""
data = []
with open(fn) as df:
for num, row in enumerate(csv.reader(df, delimiter=delim)):
if len(row) > colnum:
data.append((num, row[colnum]))
return data
# Process command-line arguments.
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument(
"-r",
"--rows",
nargs=2,
type=int,
metavar=("min", "max"),
help="only show rows min--max",
)
parser.add_argument(
"-d", "--delimiter", default=";", help="delimiter to use (defaults to ';')"
)
parser.add_argument(
"column", type=int, help="number of the column to print (starts at 0)"
)
parser.add_argument("path", type=str, nargs="*", help="path of the file to process")
args = parser.parse_args(sys.argv[1:])
# Process files
for path in args.path:
print("file:", path)
results = getdata(path, args.column, args.delimiter)
if args.rows:
rg = range(args.rows[0], args.rows[1] + 1)
results = [(n, d) for n, d in results if n in rg]
for n, d in results:
print("row {:2d}: '{}'".format(n, d))