使用** kwargs创建.txt文档

时间:2017-10-25 19:39:58

标签: python python-3.x keyword-argument

如何将**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")

1 个答案:

答案 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时,上下文会自动关闭文件。