[英]How do I convert a Python UUID into a string?
我需要能夠為用戶分配 UUID 並將其記錄在 a.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'
我想出了一個不同的解決方案,它在Python 3.7 中按預期對我有用。
import uuid
uid_str = uuid.uuid4().urn
your_id = uid_str[9:]
urn是 UUID 作為RFC 4122 中指定的URN 。
[更新] 我添加了 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()
我想這對我有用
這可能是因為您實際上並未關閉文件。 這可能會導致問題。 您想在處理文件時使用上下文管理器/ 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)
這將在您完成后自動關閉您的文件,這將確保它被寫入磁盤。
f-string 也適用:
import uuid
str_id = f'{uuid.uuid4()}'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.