Speed Demo
Speed Demo

Reputation: 21

Writing from a dictionary to a text file in a sorted way (python)

I have a code where i need to write a dictionary to a .txt file in order.

with open("Items.txt", "w+") as file:
    for item in sorted(orders):
        file.write(item + "," + ",".join(map(str,orders[item])) + "\n")
        file.close      

        print("New stock level to file complete.")

Here orders is my dictionary which i want to write into Items.txt

Every time i run this i get a type error like this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

My contents of my dictionary are:

orders[int(code)] = [str(name),int(current_stock),int(re_order),int(target_stock),float(price)]

Can some one please help me with this issue. I suspect that all the contents are not string but i don't know how to change the contents in the dictionary to a string.

PS: I cant change the contents in my dictionary to string as i need to use integer for later.

Upvotes: 0

Views: 112

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96171

Because item will be an int, you cannot use the + operator with it on a string (,). Python is a strongly typed language. Use:

file.write(str(item) + "," + ",".join(map(str,orders[item])) + "\n")

instead.

Upvotes: 1

Related Questions