Here’s the entirety of my code:
import csv
def numbersOut():
for i in range (1, 1001):
out.writerow("%s" % (i+1, ))
out.writerow("\n")
csvname = raw_input("Enter desired filename: ")
headers = ["ID", "Student", "Grade"]
out = csv.writer(open(csvname + ".csv","w"), delimiter=',', lineterminator='\n', quoting=csv.QUOTE_ALL)
out.writerow(headers)
out.writerow(numbersOut())
And the section that’s throwing up the “sequence expected” error is line 14, namely this one: out.writerow(numbersOut())
Basically, what I’m trying to do is use the function numbersOut() to put 1000 rows in a CSV file, each with it’s own ID (Line 1 (Minus headers) will = 1, Line 2 will = 2, etc). I managed to get them all on one row by using range, but that’s not what I’m needed.
However, I keep getting an error when trying to use my function. I’m not sure if it’s a problem with how I’m calling it or whether it’s a problem within the function itself.
Any ideas? If anything needs clarifying, please ask; I have a habit of not making much sense.
Thanks in advance!
EDIT: Traceback, as requested:
Traceback (most recent call last):
File "writer.py", line 14, in <module>
out.writerow(numbersOut())
_csv.Error: sequence expected
In Python, if a function falls off the end without returning, it is assumed to return
None. YournumbersOut()function doesn’treturnanything. So, when you writeyou end up calling
out.writerow(None). This will give you the error you’re seeing, asNoneisn’t a sequence and thecsvmodule doesn’t know how to write outNoneas a row of CSV data.I think you would be better off declaring
numbersOutto takeoutas an argument:and then call it using
There are another couple of changes I’d recommend making.
If you only want to write a single value to a row, replace the line
with
(note the inserted
[and]).writerowtakes a sequence of values and writes each value out into a separate comma-separated cell. If you pass a single string, that gets interpreted as a sequence of characters, and each character ends up in its own cell.Secondly, I’d recommend removing the line
out.writerow("\n"). When you write a row usingwriterow, thecsvmodule will output the end-of-line for you. There’s no need for you to end the lines manually. In fact, the lineout.writerow("\n")ends up writing a cell containing a newline between each row that contains a number.