简体   繁体   中英

Python sorted() skip row with empty coloumn

I have a CSV delimited by a '|'. I am trying to read the CSV, sort by the 8th column, and output the sorted data as a standard CSV to the stdout. The issue is that some rows in input CSV do not have an 8 column. Those rows without a column 8 can be skipped entirely. Right now when it hits a row without a column 8 it throws the error "list index out of range". If I could just get it to continue and ignore that row it would be perfect.

Any help would be appreciated. Certainly willing to change the block of code entirely.

with open(sys.argv[1]) as openFile:
    reader = csv.reader((x.replace('\0','') for x in openFile), delimiter='|')
    col = 8
    sortedReader = sorted(reader, key=lambda k: (k[col] is None, k[col] == "", k[col]), reverse=True) # This was my attempted solution found on Google/StackOverflow.  Does not work. 
    csvout = csv.writer(sys.stdout, delimiter=',')
    for row in sortedReader:
        try:
            csvout.writerow(row)
        except:
            sys.stderr.write('[!] Error in row')
            sys.stderr.write(row)
            continue

只是在排序之前过滤行

filteredRows = filter(lambda x: len(x) > col, reader)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM