Skipping lines, csv Dict Reader Python

I have a file that has an unpleasant preface to the header. So it looks like this:

Review performed by: Meeting: Person: Number: Code: Confirmation Tab Separated Header Names That I Want To Use 

I want to skip everything and use the sep tab header names for my code. This is what I have so far:

 reader = csv.DictReader(CSVFile) for i in range(14): #trying to skip the first 14 rows reader.next() for row in reader: print(row) if args.nextCode: tab = (row["Tab"]) sep = int((row["Separated"])) 

This code gets this error:

 File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 104, in next row = self.reader.next() StopIteration 

I tried to print the lines to see where I was in the file, and I changed "range (14)" to range 5, but when I print the line, I get the following:

 {'Review performed by:': 'Tab/tSeparated/tHeader/tNames/tThat/tI/tWant/tTo/tUse'} Traceback (most recent call last): File "program.py", line 396, in <module> main() File "program.py", line 234, in main tab = (row["Tab"]) KeyError: 'Tab' 

So I'm not sure if the surest way to skip these top lines is. Any help would be greatly appreciated.

+6
source share
2 answers

A csv.DictReader reads the first line from a file when it is created to get headers for subsequent lines. Therefore, it uses Review performed by: as the title bar, then you skip the next 14 lines.

Instead, skip the lines before creating the DictReader :

 for i in range(14): CSVFile.next() reader = csv.DictReader(CSVFile) ... 
+14
source

You can wrap the CSVFile with the iterator itertools.islice to cut the preface lines when creating the DictReader instead of providing it directly to the constructor.

This works because the csv.reader constructor accepts any "object that supports the iterator protocol and returns a string every time its next() method is called" according to csv docs . This also applies to csv.DictReader , because they use an internal reader instance inside.

 N = 14 # number of lines to skip for row in csv.DictReader(itertools.islice(CSVFile, N, None)): process row ... 
+2
source

Source: https://habr.com/ru/post/989688/


All Articles