Reputation: 41
I am currently attempting to parse two different types of files using python's csv module. In order to discover which file I am attempting to parse, I have to read the first letter of the second line. Depending on what that line says, I would like to move to either line 7 or line 4 then use csv to read in the data. I read that it doesn't work to mix readline() and next() on a file object. Is there a different way to move down lines? This is my current code to give a better idea of what I am attempting:
with open(str(new_file)) as new_file:
new_file.next()
line2 = new_file.readline()
# Check to see which file it is
if line2[0] == "P":
# Move to line 7
else:
# Move to line 4
# Read in the contents of the file and get rid of whitespace
list_of_dicts = list(csv.DictReader(new_file, delimiter = " ", skipinitialspace = True))
If anyone has an idea of how to deal with this, that would be fantastic.
Upvotes: 0
Views: 778
Reputation: 10784
line2 = new_file.next() # now pointing at line 3
if line2[0] == "P":
for _ in xrange(4):
new_file.next() # skip lines 3, 4, 5, 6
else:
new_file.next() # skip line 3 only
Upvotes: 1