3 Replies - 610 Views - Last Post: 01 June 2011 - 01:22 PM Rate Topic: -----

#1 tootypegs  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 239
  • Joined: 09-October 07

outputting to file

Posted 01 June 2011 - 06:59 AM

Im stuck with outputting to a file because of the complexity of the structure of the list im outputting. I think!

it looks like this

[('Scott Sinclair', 1, 2), ('Reading comeback', 1, 2), ('Premier League', 1, 2)]

the bracketed entries can vary though, some times there could be more or less.


for item in thelist:
thefile.write("%s\n" % item)   # thefile is the stream  thelist is the list structure




i get the error not all arguments converted during string formatting

i think my list is a bit weird, but it has to stay in that structure

Is This A Good Question/Topic? 0
  • +

Replies To: outputting to file

#2 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: outputting to file

Posted 01 June 2011 - 07:02 AM

Could you please list a couple more samples of data?
Also show how they should be formatted in the final file.
Was This Post Helpful? 0
  • +
  • -

#3 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: outputting to file

Posted 01 June 2011 - 01:13 PM

You have to serialize the items in thelist before writing them to a file/stream. Serializing means to compute some string representation for those items. (And unserializnig means to recreate the data objects from their string representation)

If all your items are such simple (just a tuple of strings and numbers) you could use str() for serialization and eval() for unserialization:

#write list to file
for item in thelist:
    thefile.write("%s\n" %str(item))

#read list from file
readlist = []
for line in the thefile:
    readlist.append(eval(line.strip()))



For more complex data to be serialized you may want to look at the json, marshal or pickle modules of pythons standard library.

This post has been edited by Nallo: 01 June 2011 - 01:14 PM

Was This Post Helpful? 0
  • +
  • -

#4 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: outputting to file

Posted 01 June 2011 - 01:22 PM

If all your entries are simply string, int, int, you may want to consider using a database.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1