简体   繁体   中英

print key into txt file

So I am working on a script to generate serialnumbers for a product. I want to make a txt file where I the script prints the generated key. somehow it cant print in there but I don't know what I need to changes about it.

key = Key('aaaa-bbbb-cccc-dddd-1111')

fh = open('key.txt')

fh.write(Key)

Try:

key = "Key('aaaa-bbbb-cccc-dddd-1111')"
fh = open('key.txt', "w")
fh.write(key)

To generate a text file that doesn't already exist you need to use "w" .

Try doing:

key = Key('aaaa-bbbb-cccc-dddd-1111')
    
with open('key.txt', 'w') as fh: 
    fh.write(key)

Hope that Helps: Note: it must be in the with... so it writes, if its not there the file is considered as closed.

Ok, based on your response, I've mocked up the Key class as follows. Without more information, it's not possible to give you a definitive answer, but hopefully this helps!

class Key:
    def __init__(self, serial):
        self.serial = serial

    def process_serial(self):
        # Your processing here
        ...
        return processed_serial  # This should be a string

Then to write to file, you can do:

key = Key('aaaa-bbbb-cccc-dddd-1111')

with open('key.txt', 'w') as f:
    f.write(key.process_serial())

Alternatively, you can add a __str__ method to your class, which will specify what happens when you call the Python builtin str on your object.

class Key:
    def __init__(self, serial):
        self.serial = serial

    def __str__(self):
        out = ...  # construct what you want to write to file
        return out

Giving:

key = Key('aaaa-bbbb-cccc-dddd-1111')

with open('key.txt', 'w') as f:
    f.write(str(key))

You might also consider adding this as a method to your Key class

class Key:
    __init__(self, serial):
        self.serial = serial

    def process_serial(self):
        # Your processing here
        ...
        return processed_serial  # This should be a string

    def write(self, file_name):
        with open(file_name, 'w') as f:
            f.write(self.process_serial)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM