How do I convert a Python UUID into a string?

PythonStringUuid

Python Problem Overview


I need to be able to assign a UUID to a user and document this in a .txt file. This is all I have:

import uuid

a = input("What's your name?")
print(uuid.uuid1())
f.open(#file.txt)

I tried:

f.write(uuid.uuid1())

but nothing comes up, may be a logical error but I don't know.

Python Solutions


Solution 1 - Python

you can try this !

 a = uuid.uuid1()
 str(a)
 --> '448096f0-12b4-11e6-88f1-180373e5e84a'

Solution 2 - Python

You can also do this. Removes the dashes as a bonus. link to docs.

import uuid
my_id = uuid.uuid4().hex

ffba27447d8e4285b7bdb4a6ec76db5c

UPDATE: trimmed UUIDs (without the dashes) are functionally identical to full UUIDS (discussion). The dashes in full UUIDs are always in the same position (article).

Solution 3 - Python

I came up with a different solution that worked for me as expected with Python 3.7.

import uuid

uid_str = uuid.uuid4().urn
your_id = uid_str[9:]

urn is the UUID as a URN as specified in RFC 4122.

Solution 4 - Python

[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

 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

Solution 5 - Python

It's probably because you're not actually closing 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 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlphin PhilipView Question on Stackoverflow
Solution 1 - PythonsumitView Answer on Stackoverflow
Solution 2 - PythonandywView Answer on Stackoverflow
Solution 3 - PythonabdullahselekView Answer on Stackoverflow
Solution 4 - PythonEliethesaiyanView Answer on Stackoverflow
Solution 5 - PythonWayne WernerView Answer on Stackoverflow