1

I am currently doing a project for school that involves making a graphing editor. I am at a part where I have to be able to save and reopen the file. I can open the file but I have to iterate through it and regraph everything I saved. I am unsure however to actually iterate through the file because when print the file that I opened, i get a huge list that has all of my lists within it like this:

["['Rectangle', 5.168961201501877, 8.210262828535669, 7.6720901126408005, 6.795994993742178, 'red']['Line', 5.782227784730914, 5.269086357947434, 8.69837296620776, 4.993742177722153, 'red']['Circle', 2.6491232154288933, -0.8552572601656006, 6.687547623119292, 3.1831671475247982, 'red']"]

I am new at using this website so please bear with me.

def open_file(self,cmd):
    filename=input("What is the name of the file? ")
    File= open(filename,'r')
    file= File.readlines()
    print(file)

I had previously saved the file by using:

file.write(str(l)) where l is the name of a list of values I made

I have tried using split() I tried using a for loop to save the data within the string into a list and I have searched the web for hours to find some sort of explanation but I couldn't find any.

4
  • You should indicate what you have already tried, what happened, and what you were hoping for. Apr 25, 2014 at 0:29
  • How do you store the data in the file and how do you reload it? We'd like to see the relevant bits of your code (with the irrelevant bits removed). Apr 25, 2014 at 0:36
  • Is there a requirement that states you cannot use JSON or a pickle? I think that would solve all your problems. Apr 25, 2014 at 0:54
  • @SethMMorton it is a beginner python class so I am not sure what either of those are, we haven't discussed them
    – Deez1133
    Apr 25, 2014 at 0:59

2 Answers 2

1

What you've provided is actually a list with one item consisting of a long string. Can you provide the code you're using to generate this?

If it actually is a list within a list, you can use a for loop inside another for loop to access each item in each list.

let's say your list is object l.

l[0] = ['Rectangle', 5.168961201501877, 8.210262828535669, 7.6720901126408005, 6.795994993742178, 'red']

and l[0][0] = 'Rectangle'

for i in l:
    for x in i:

Would allow you to loop through all of them.

For the info you've provided, readlines() won't necessarily work, as there's nothing to delineate a new line in the text. Instead of saving the list as a converted string, you could use a for loop to save each item in the list as a line

for lne in l:
    f.write(lne)

Which would write each item in the list on a new line in the file (depending on your python version, you might have to use f.write(lne+'\n') to add a new line). Then when you open the file and use readlines(), it will append each line as an item in a list.

0
0

You are apparently having problem with reading data you have created before.

Your task seem to require

1) creating some geometry in an editor

2) serialize all the geometry to a file

and later on (after the program is restarted and all old memory content is gone:

3) load geometries from the file

4) recreated the content (geometries) in your program

In step 2 you did something and you seem to be surprised by that. My proposal would be to use some other serialization option. Python offers many of them, e.g.

  • pickle - quick and easy, but is not interoperable with other than Python programs
  • JSON - easy, but might require some coding for serialization and loading your custom objects

Sample solution using JSON serialization could go like this:

import json

class Geometry():
    def __init__(self, geotype="Geometry", color="blank", numbers=[]):
        self.geotype = geotype 
        self.color = color
        self.numbers = numbers

    def to_list(self):
        return [self.geotype, self.color, self.numbers]

    def from_list(self, lst):
        print "lst", lst
        self.geotype, self.color, self.numbers = lst
        return self

    def __repr__(self):
        return "<{self.geotype}: {self.color}, {self.numbers}>".format(self=self)

def test_create_save_load_recreate():
    geoms = []
    rect = Geometry("Rectange", "red", [12.34, 45])
    geoms.append(rect)

    line = Geometry("Line", "blue", [12.33, 11.33, 55.22, 22,41])
    geoms.append(line)

    # now serialize
    fname = "geom.data"
    with open(fname, "w") as f:
        geoms_lst = [geo.to_list() for geo in geoms]
        json.dump(geoms_lst, f)
    # "geom.data are closed noe
    del f
    del geoms
    del rect
    del line
    # after a while
    with open(fname, "r") as f:
        data = json.load(f)
    geoms = [Geometry().from_list(itm) for itm in data]
    print geoms
4
  • "pickle - quick and easy, but is not interoperable with other then Python programs" - Not true. Maybe you meant not guaranteed to be interoperable between different python versions? Apr 25, 2014 at 1:16
  • @SethMMorton by "other then Python programs" I mean "any program written in something else than Python". Apr 25, 2014 at 1:18
  • Ah, you meant "than", not "then". The difference in vowel made me interpret that sentence incorrectly. Apr 25, 2014 at 1:19
  • @Deno1133 You are welcome. If mine or other solution solve your question, consider accepting it as an answer. At the same time you can upvote any other answer, if you find it useful. Apr 25, 2014 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.