如何将**kwargs
放入我新创建的.txt文档中?
def credentials_file(filename, **kwargs):
open(filename, "w")
for key, value in kwargs.items():
filename.write("{}: {}\n" .format(key, value))
credentials_file("credentials.txt", First_Name="John",
Last_Name="Cleese")
答案 0 :(得分:5)
open(filename, "w")
不将filename
从字符串转换为文件处理程序,它会打开文件(有时会创建文件)并且< strong>返回句柄。
所以你应该使用:
def credentials_file(filename, **kwargs):
handle = open(filename, "w")
for key, value in kwargs.items():
handle.write("{}: {}\n" .format(key, value))
handle.close()
但是如果是句柄,最好使用with
上下文:
def credentials_file(filename, **kwargs):
with open(filename, "w") as handle:
for key, value in kwargs.items():
handle.write("{}: {}\n" .format(key, value))
当你跳出with
时,上下文会自动关闭文件。