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?
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))
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.