fiz
fiz

Reputation: 936

Manipulating a Write File Class

The following classes work, I'm just trying to manipulate the top class to work for me:

This class writes the file:

class saveRegister :
    def __init__( <--snip--> #defines some of the variables in the write function

    def writeToFile(self,file) :

        file.write(... #saves values in a specific format

This used the above class to write is what I based mine very quickly on:

class Prep :
    def writeToFilename( self, filename, registerNames ) :
        file = open( filename, 'w+' )
        for register in self.registers : #format here same as in my code
            register.writeToFile(file)
        file.close()

I'm trying to reuse their code to work with mine in a different file, but can't figure out what I'm doing wrong. As a quick test, I wanted to write this to a file using the above:

from mylib.saveFiles import saveRegister

def saveStateValues(self, msg):

    filename="/tmp/test.txt"
    reg_test = {"HelloWorld":0x5}

    file.open(filename, 'w+')
    for register in reg_test:
        register.saveRegister.writeToFile(file)
    file.close()

The written file isn't even displayed which is strange because when I've used the file.open() method before here, it works. I can't give you an error message as there are none (for various annoying reasons, this is translated into Java - but that shouldn't be important, so when something subtle doesn't work, it just doesn't tell you).

Upvotes: 1

Views: 53

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

I'm not entirely clear what you are doing, but there are rather a lot of bugs in your saveStateValues method.

file is a built-in function in Python - it is actually a synonym for open - and there is no such thing as file.open. The function returns an opened file, but you throw that away rather than storing it in a variable: then you pass the function itself into your writeToFile, rather than the file you've just opened.

Then there are even more issues with your loop. You iterate through reg_test, which is a dictionary, so each value of register is a key from that dict. But for some reason you treat that as an object and try to access its saveRegister attribute. saveRegister is a class you've imported, so that makes no sense. What you should be doing is instantiating an instance of saveRegister outside the loop, then passing each value to the writeToFile method.

Putting it all together:

file_to_write = open(filename, 'w+')
save_register = saveRegister()
for register in reg_test:
    save_register.writeToFile(file_to_write, register)
file_to_write.close()

(I'm pretty sure this is not totally correct, because you aren't doing anything with the values from reg_test, just the keys. We probably need to know what exactly saveRegister.writeToFile is expecting.)

Upvotes: 1

Related Questions