Skip to content

Instantly share code, notes, and snippets.

@Saigesp Saigesp/catcsv.py
Created Sep 23, 2018

Embed
What would you like to do?
Para recortar archivos CSV desde la linea de comandos
# -*- coding: utf-8 -*-
import sys
import csv
from collections import deque
from itertools import islice
def skip_last_n(iterator, n=1):
it = iter(iterator)
prev = deque(islice(it, n), n)
for item in it:
yield prev.popleft()
prev.append(item)
def file_cat(opt):
print('')
sc = int(opt['skip_columns'])
slc = int(opt['skip_last_columns'])
try:
with open(opt['filepath'], encoding='latin-1') as data_file:
reader = csv.reader(data_file, delimiter=";")
for n in range(int(opt['skip_rows'])):
next(reader)
if int(opt['skip_last_rows']):
iterator = skip_last_n(reader, n=int(opt['skip_last_rows']))
else:
iterator = reader
datadict = []
columns = []
for idx, row in enumerate(iterator):
if opt['limit_rows'] != False:
if idx == int(opt['limit_rows']):
break
if slc > 0:
print(row[sc:slc*(-1)])
else:
print(row[sc:])
print('')
except Exception as e:
print('No se puede leer el archivo')
print(e)
def msg_help():
print('')
print(' -f FILE PATH')
print(' <rutal del archivo>')
print('')
print(' OPCIONES')
print(' -sr <int> # Skip n rows')
print(' -slr <int> # Skip last n rows')
print(' -lr <int> # Limit n rows')
print('')
print(' -sc <int> # Skip n columns')
print(' -slc <int> # Skip last n columns')
print(' -lc <int> # Limit n columns')
print('')
print(' Ejemplos:')
print('')
print(' python3 -m geotools.import_padron -f "/path/file.csv"')
print(' python3 -m geotools.import_padron -f "/path/file.csv" -lr 26')
print(' python3 -m geotools.import_padron -f "/path/file.csv" -sr 4 -lr 10 -lc 10')
print(' python3 -m geotools.import_padron -f "/path/file.csv" -sr 4 -slr 6 -slc 1 -k 0 -v 2')
print('')
if __name__ == "__main__":
options = {
'filepath': {
'key': '-f',
'value': False,
},
'skip_rows': {
'key': '-sr',
'value': 0,
},
'skip_last_rows': {
'key': '-slr',
'value': 0,
},
'limit_rows': {
'key': '-lr',
'value': False,
},
'skip_columns': {
'key': '-sc',
'value': 0,
},
'skip_last_columns': {
'key': '-slc',
'value': 0,
},
'limit_columns': {
'key': '-lc',
'value': False,
},
}
opt = {}
arguments = False
for k, v in options.items():
opt[k] = v['value']
if v['key'] in sys.argv:
idx = sys.argv.index(v['key'])
opt[k] = sys.argv[idx+1]
if '-h' in sys.argv:
msg_help()
elif opt['filepath']:
file_cat(opt)
else:
msg_help()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.