i am catherine. I just now started to learn python.
import random
import csv
a={"1":1}
print(len(a))
for i in range(100):
x=random.randint(1, 100)
a[i] = x
print(a)
with open('random.csv', 'w', newline='') as csvfile:
fields = ['QNO', 'RQNO']
writer = csv.DictWriter(csvfile, fieldnames=fields)
writer.writeheader()
for i in range(101):
#j=a[i]
#print(i,j)
writer.writerow({'QNO':i , 'RQNO': a[i]})
file.close()
i get err
Error:
File "e:\phy-prg\4.py", line 18, in <module>
csvwriter.writerow({'QNO':i , 'RQNO': a[i]})
NameError: name 'csvwriter' is not defined. Did you mean: 'writer'?
(Sep-01-2022, 12:51 PM)cathy12 Wrote: [ -> ]i am catherine. I just now started to learn python.
Hi @
cathy12 and welcome to the forum. Please start a new thread describing the issue: go to the
General Coding Help forum, or perhaps the homework forum if this is homework and push the « Post Thread » button. Don't forget to use
Code Tags to display Python code in your post.
(Sep-01-2022, 12:51 PM)cathy12 Wrote: [ -> ]i get err
The error message is not consistent with the code. Also the
for
loop should be indented inside the
with open...
section because it uses the object
writer
which exists only in this with section.
On the face of this (as I've not in fact tested it) I can see that the file is being close at line 14: you're using a context manager with open() as
and as such you don't need line 19, which is the way to do things, so you'll want to move the for
loop, which starts at line 15, inside the file context manager: simple indent the loop by four spaces.
See how that goes and report back if you have any more issues.
n.b: I've not tested any of this, so there could be another bug or two to squish.
edit to add...
I've just spotted this at line 6: for i in range(100):
Change that to: for i in range(101):
You are not using DictWriter the way it is meant to be used. csv.DictWriter can be used that way, but it is far easier to use a csv.writer object to do what you want.
import random
import csv
with open("random.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(("QNO", "RQNO")) # Writing the column headers
for index in range(5):
writer.writerow((index, random.randint(1, 100)))
random.csv
Output:
QNO,RQNO
0,3
1,56
2,69
3,6
4,56
DictWriter is used when you already have dictionaries that you want to write.
import random
import csv
# Make some fake dictionary data. Add an extra field for DictWriter to filter out.
random_dict = [{"QNO": i, "RQNO": random.randint(1, 100), "ZERO":0} for i in range(5)]
with open("random.csv", "w", newline="") as csvfile:
fields = ("QNO", "RQNO")
writer = csv.DictWriter(csvfile, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(random_dict)
random.csv
Output:
QNO,RQNO
0,91
1,27
2,78
3,6
4,87