Python 如何将 UUID 更改为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37049289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change a UUID to a string?
提问by Alphin Philip
I need to be able to assign a UUID to a user and document this in a .txt file. This is all I have:
我需要能够为用户分配 UUID 并将其记录在 .txt 文件中。这就是我所拥有的:
import uuid
def main():
a=input("What's your name?")
print (uuid.uuid1())
f.open(#file.txt)
main()
I tried:
我试过:
f.write(uuid.uuid1())
but nothing comes up, may be a logical error but I don't know.
但什么也没有出现,可能是逻辑错误,但我不知道。
回答by sumit
you can try this !
你可以试试这个!
a = uuid.uuid1()
str(a)
--> '448096f0-12b4-11e6-88f1-180373e5e84a'
回答by abdullahselek
I came up with a different solution that worked for me as expected with Python 3.7.
我想出了一个不同的解决方案,它在Python 3.7 中按预期对我有用。
import uuid
uid_str = uuid.uuid4().urn
your_id = uid_str[9:]
urnis the UUID as a URNas specified in RFC 4122.
urn是 UUID 作为RFC 4122 中指定的URN。
回答by Eliethesaiyan
[update] i added str function to write it as string and close the file to make sure it does it immediately,before i had to terminate the program so the content would be write
[更新] 我添加了 str 函数将其写为字符串并关闭文件以确保它立即执行,然后我不得不终止程序以便写入内容
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()
I guess this works for me
我想这对我有用
回答by Wayne Werner
It's probably because you're not actuallyclosing your file. This can cause problems. You want to use the context manager/with
block when dealing with files, unless you really have a reason not to.
这可能是因为您实际上并未关闭文件。这可能会导致问题。你想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)
This will automatically close your file when you're done, which will ensure that it's written to disk.
这将在您完成后自动关闭您的文件,这将确保它被写入磁盘。