[英]print key into txt file
所以我正在編寫一個腳本來為產品生成序列號。 我想制作一個 txt 文件,腳本在其中打印生成的密鑰。 不知何故,它不能在那里打印,但我不知道我需要改變它。
key = Key('aaaa-bbbb-cccc-dddd-1111')
fh = open('key.txt')
fh.write(Key)
嘗試:
key = "Key('aaaa-bbbb-cccc-dddd-1111')"
fh = open('key.txt', "w")
fh.write(key)
要生成一個尚不存在的文本文件,您需要使用"w"
。
嘗試做:
key = Key('aaaa-bbbb-cccc-dddd-1111')
with open('key.txt', 'w') as fh:
fh.write(key)
希望有幫助: 注意:它必須在with...
中,所以它會寫入,如果它不存在,則文件被視為已關閉。
好的,根據您的回復,我將Key
class 模擬如下。 沒有更多信息,不可能給你一個明確的答案,但希望這會有所幫助!
class Key:
def __init__(self, serial):
self.serial = serial
def process_serial(self):
# Your processing here
...
return processed_serial # This should be a string
然后寫入文件,你可以這樣做:
key = Key('aaaa-bbbb-cccc-dddd-1111')
with open('key.txt', 'w') as f:
f.write(key.process_serial())
或者,您可以向 class 添加一個__str__
方法,該方法將指定當您在 object 上調用 Python 內置str
時會發生什么。
class Key:
def __init__(self, serial):
self.serial = serial
def __str__(self):
out = ... # construct what you want to write to file
return out
給予:
key = Key('aaaa-bbbb-cccc-dddd-1111')
with open('key.txt', 'w') as f:
f.write(str(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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.