在创建文件时,如何将uuid.uuid4()值与文字连接?以下是不正确的,但应说明我正在尝试做什么...
fo = open(uuid.uuid4() + ".txt", "wb")
答案 0 :(得分:33)
您需要将uuid
转换为str
:
>>> import uuid
>>> str(uuid.uuid4()) + ".txt"
'13eb9327-f40e-4ef1-8020-1c36af1b4b70.txt'
答案 1 :(得分:3)
此版本不包含字符串
中的-
fo = open(uuid.uuid4().hex + ".txt", "wb")
使用上下文管理器
打开文件通常是个好主意with open(uuid.uuid4().hex + ".txt", "wb") as fo:
# do stuff with fo
# fo will be closed automatically
以下是循环中的示例
for item in data:
with open(uuid.uuid4().hex + ".txt", "wb") as fo:
fo.write(item)