2

I have a ten line CSV file. From this file, I only want the, say, fourth line. What's the quickest way to do this? I'm looking for something like:

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    print reader[3]

where reader[3] is obviously incorrect syntax for what I want to achieve. How do I move the reader to line 4 and get it's content?

1 Answer 1

6

If all you have is 10 lines, you can load the whole file into a list:

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    rows = list(reader)
    print rows[3]

For a larger file, use itertools.islice():

from itertools import islice

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    print next(islice(reader, 3, 4))
Sign up to request clarification or add additional context in comments.

3 Comments

Is the time complexity of printing one line from a CSV file (done this way) O(1)? If not, is there a way to read a line from a CSV file, in constant time?
@Mencia: your question is muddled. First you talk about printing, then reading a line. Next, Big O deals in asymptotic behaviour, stating how the time taken changes as the number of items processed changes, if you were to increase the number of items to infinity. So for one line out of N lines, there is usually little point in talking about O(...) performance. If it's one line, it's one line, so always O(1) compared to the whole file.
@Mencia: Next, file I/O involves lots of buffering. So next(reader), producing one line from the CSV file triggers a buffered read, reading a block of data into the Python process, to then be decoded from bytes, and then the next line separator needs to be located, and then the CSV module needs to split the line of text into columns. The I/O buffer read is going to be the slowest and as long as the first row fits in that block (about 8 kliobytes, typically), you'll not see any difference in performance regardless of file size or row length. There is no point in worrying about this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.