osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

how to get a value from CSV specific cell (A7) thanks


alon.najman at gmail.com wrote:

> how to get a value from CSV specific cell (A7) thanks

$ cat csv_sheet.py               
#!/usr/bin/python3
import re
import csv
import string

LOOKUP = {c: i for i, c in enumerate(string.ascii_uppercase, 1)}

def a2i(s):
    """
    >>> a2i("A")
    0
    >>> a2i("Z")
    25
    >>> a2i("AA")
    26
    >>> a2i("AZ")
    51
    >>> a2i("BA")
    52
    """
    sigma = 0
    for c in s:
        sigma *= len(LOOKUP)
        sigma += LOOKUP[c]
    return sigma - 1

def offset(s):
    m = re.match("([A-Z]+)([0-9]+)", s.upper())
    if m is None:
        raise ValueError
    col, row = m.groups()
    return a2i(col), int(row) - 1

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("file")
    parser.add_argument("cells", metavar="cell", nargs="+")
    args = parser.parse_args()

    with open(args.file) as f:
        rows = list(csv.reader(f))
    for cell in args.cells:
        x, y = offset(cell)
        print(rows[y][x])
$ cat tmp.csv
1,2,3,4,5,6,7,8,9
10,20,30,40,50,60,70,80,90
100,200,300,400,500,600,700,800,900
1000,2000,3000,4000,5000,6000,7000,8000,9000
10000,20000,30000,40000,50000,60000,70000,80000,90000
100000,200000,300000,400000,500000,600000,700000,800000,900000
1000000,2000000,3000000,4000000,5000000,6000000,7000000,8000000,9000000
$ ./csv_sheet.py tmp.csv a7 b2 c3
1000000
20
300
$ python3 -m doctest csv_sheet.py  # otherwise untested