我给你一个例子,我点击运行在控制台上写一个数字(多少个键),然后我得到这个随机的字母和数字:61PYY-ZEPY1-2H82R-V1JZ1-9VEF7,但是我希望它们在我的demofile2中。文本。当我将其粘贴到写入中时:'-'。join(''。join(random.choice(seq)for range(5)中的_)for range in(5)中的_)表示seq没有定义
这是代码:
import random, sys
class KeyGen():
def __init__(self):
global i
i = int(input("How many serial codes are you looking for? \n"))
print("")
self.main(i)
def main(self, count):
""" Our main iteration function, using simple
capital letters, along with the numbers 0-9 """
seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
for i in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))
print("\nCreated {} serial keys.".format(count))
if __name__ == '__main__':
app = KeyGen()
text_file = open("demofile2.txt.")
text_file.write(THISISWHATISEARCH)
text_file.close()
为了写入文件,您只需要将一个字符串传递给file.write()
。如果您使用的是您要打印的字符串。
区别在于,它print
会在每个字符串的末尾自动添加新行(由于参数的默认值end='\n'
)。因此,在写入文件时,您可以添加结尾换行符。另外,您可以使用print
的file
参数来避免任何更改!
现在,您只需要在要写入文件描述符的位置提供文件描述符即可。这可能取决于其余代码的设计,为简化示例,我将其简单地移至main
函数中。
还有一件事是在读取/写入文件时,最好使用with
上下文管理器:
import random, sys
class KeyGen():
def __init__(self):
global i
i = int(input("How many serial codes are you looking for? \n"))
print("")
self.main(i)
def main(self, count):
""" Our main iteration function, using simple
capital letters, along with the numbers 0-9 """
seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
with open("demofile2.txt.", 'w') as text_file:
for i in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
# text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')
print("\nCreated {} serial keys.".format(count), file=text_file)
# text_file.write("\nCreated {} serial keys.\n".format(count))
if __name__ == '__main__':
app = KeyGen()
我将利用这个机会作为一般性提示:
在Python中,不需要过度使用类。也许您来自Java的背景,那里的一切都是类,但是在这里,您的类仅充当函数的门户。因此,您的代码可能是:
import random, sys
def main():
"""
Our main iteration function, using simple
capital letters, along with the numbers 0-9
"""
seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
count = int(input("How many serial codes are you looking for? \n"))
with open("demofile2.txt.", 'w') as text_file:
for _ in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
# text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')
print("\nCreated {} serial keys.".format(count), file=text_file)
# text_file.write("\nCreated {} serial keys.\n".format(count))
if __name__ == '__main__':
main()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句