我需要能够为用户分配一个UUID,并将其记录在一个 .txt 文件中。这是我所拥有的全部内容:
import uuid
a = input("What's your name?")
print(uuid.uuid1())
f.open(#file.txt)
我尝试过:
f.write(uuid.uuid1())
但是没有任何结果显示,可能是一个逻辑错误,但我不知道。
你可以试试这个!
a = uuid.uuid1()
str(a)
--> '448096f0-12b4-11e6-88f1-180373e5e84a'
str(UUID)
会始终返回一个由字母数字和破折号组成的字符串吗?我找不到关于UUID.__str__()
的文档。或者,我需要使用类似于UUID.hex()
或UUID.urn()
这样的方法来确保结果字符串中没有非可打印字符吗? - Adam Mlodzinski import uuid
def main():
a=input("What's your name?")
print(uuid.uuid1())
main()
f=open("file.txt","w")
f.write(str(uuid.uuid1()))
f.close()
我想这对我来说可行
uuid.uuid1() != uuid.uuid1()
。 - djvg很可能是因为你没有真正关闭文件。这可能会导致问题。在处理文件时,除非你有充分的理由不这样做,否则应该使用上下文管理器/with
块。
with open('file.txt', 'w') as f:
# Do either this
f.write(str(uuid.uuid1()))
# **OR** this.
# You can leave out the `end=''` if you want.
# That was just included so that the two of these
# commands do the same thing.
print(uuid.uuid1(), end='', file=f)
from __future__ import print_function
。 - Wayne Wernerf-string也可以:
import uuid
str_id = f'{uuid.uuid4()}'
uuid
的文档? - Ignacio Vazquez-Abramsuuid
周围放置str(...)
来将其更改为字符串。 - khelwood