-2

I would like to print the final 13 lines of the csv file saved as updated_quotes. It is returning a syntax error. How can I fix this?

  import csv
from collections import deque

with open('updated_quotes', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)


def tail(csv_file, n=13):
    'Return the last n lines of a file'
    print(return deque(open(csv_file), n))
Ivam
  • 379
  • 3
  • 12
Jacob Smith
  • 103
  • 1
  • 6

2 Answers2

1

You should be opening the file within the tail function and pass the file object to csv.reader

import csv
from collections import deque

def tail(csv_file, n=13):
    'Return the last n lines of a file'
     with open(csv_file, 'r') as f:
         csv_reader = csv.reader(f)
         return deque(csv_reader, n) 

print (tail("updated_quotes", n=13))
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

Your immediate problem is that final line in tail is:

print(return deque(open(csv_file), n))

I'll bet you had print(deque(open(csv_file), n)) while you were developing and meant to edit it to return(deque(open(csv_file), n)).

But there's more wrong here. The tail method is never invoked. As you go further, I think you'll find that everything that uses your csv reader will need to be in side the with statement.

Try this as a starter:

import csv
from collections import deque

def tail(csv_file_name, n=13):
    'Return the last n lines of a file'
    with open(csv_file_name, 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        return(deque(csv_reader, n))

last_13 = tail('updated_quotes')
print(last_13)
codingatty
  • 2,026
  • 1
  • 23
  • 32
  • This works, but writes a weirdly formatted csv. I think it is because the rows are written with a deque instead of a string. is that right? Thank you so much for your help. I just started learning to code and got a little stuck. – Jacob Smith Jul 05 '18 at 23:45
  • Right. After reading, it's not a CSV at all, it's a deque (a double-ended queue) Put another way, the file is a csv-formatted file. The whole point of the Python csv module is to convert it *from* a csv into a series of rows of data. Usually that's a list, but it can be a deque, if that's what you need. But if you don't need a deque, and all you want are the last 13 rows of a csv file, consider using csv to just read it into a list, then slice out the last 13 rows, and write it back out using csv.writer. – codingatty Jul 06 '18 at 02:02