Pythonic way to extract first line of a tabular file to a list
Question: This is a function that takes the tabular file as input and return the first
row as list:

    
    
    def firstline_to_list(fvar):
        """
        Input tab separated file.
        Output first row as list.
        """
        import csv
        lineno = 0
        with open(fvar, 'r') as tsvfile:
            tabreader = csv.reader(tsvfile, delimiter='\t')
            for row in tabreader:
                lineno += 1
                if lineno == 1:
                    return row
                    break
    

Is there a better way to do it than this clunky code of mine?


Answer: Just replace your for loop with a single call of `next` on the iterator
`tabreader`. In python 2.7, this should be `tabreader.next()`, and in python
3, I think it's `next(tabreader)`. You might also want to wrap the call in
`try except` block for `StopIteration` exception, just in case the file is
empty.

So putting everything together, here's version that's compatible with python 2
and 3:

    
    
    def firstline_to_list(fvar):
        """
        Input tab separated file.
        Output first row as list.
        """
        import csv, sys
    
        with open(fvar, 'r') as tsvfile:
            tabreader = csv.reader(tsvfile, delimiter='\t')
            try:
                if sys.version > '3':
                    result = next(tabreader)
                else:
                    result = tabreader.next()
            except StopIteration:
                result = None
    
        return result
    

