I am trying to write my dictionary to a csv and i am getting errors, was wondering if someone could tell me what i am doing wrong

this is my function

n = open(file.csv,"w")
for item in my_dict.items():
		f.write(item)
f.close()

my my_dict is for example {john }

when i use the function i get the error: expected a character buffer object but if i replace the write with print it works.

thanks in advance

Recommended Answers

All 9 Replies

I do not understand line 3, I think file class has not csv attribute. n is also never used.

im sorry i wrote it wrong

n = open("file.csv","w")
for item in my_dict.items():
		f.write(item)
n.close()

i get the error "error: expected a character buffer object"

but for example if i put it like this

n = open("file.csv","w")
for item in my_dict.items():
		print item
n.close()

it displays everything correctly on the screen, cant figure out what i am doing wrong

f is never declared and so is not a character buffer.

f is never declared and so is not a character buffer.

please see my updated post above yours

Please see line 3 in the first/top program in that post. If you had included the entire error message in the first place it would have shown that that was the error line and saved everyone some time.

i tried to edit the first post but it didnt allow me so i had to create another post and i actually included the error message in the first post.

Anyways can someone help with my problem?

Thanks in advance

n = open("file.csv","w")
for item in my_dict.items():
		n.write(item)
n.close()

A complete error message is like the following and greatly increases your chances of receiving some help.

my_dict = {1:"1"}
n = open('file.csv',"w")
for item in my_dict.items():
		f.write(item)
f.close()

"""
Traceback (most recent call last):
  File "./test_1.py", line 94, in <module>
    f.write(item)
NameError: name 'f' is not defined
"""

ok this is what i get

my_dict = {1:"1"}
>>> n = open('file.csv',"w")
>>> for item in my_dict.items():
	n.write(item)

	

Traceback (most recent call last):
  File "<pyshell#12>", line 2, in <module>
    n.write(item)
TypeError: expected a character buffer object

I've overlooked the obvious. It should be

for key, item in my_dict.items():

Hopefully it works now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.