【问题标题】:How to write list of parameter names and values in txt?如何在txt中写入参数名称和值列表?
【发布时间】:2020-10-31 00:08:36
【问题描述】:

我的 python 脚本存在以下问题: 有很多计算,我想把一些最终的结果写成一个文本文件。

这是我迄今为止尝试过的:

a1=3
a2=5
a3=10
a4=15

setupfile = open("setupfile.txt","w")
x = [a1,a2,a4]
for name in x:
    setupfile.write("name" + "=" + repr(name) +"\n")
setupfile.close()

电流输出:

name=3
name=5
name=15

预期输出:

a1=3
a2=5
a4=15

【问题讨论】:

  • 您希望文本文件在单独的行中包含a1=3, a2=5, a4=15 吗?
  • 是的,这正是我想要的
  • @Vallepu 将所有相关变量放在dict 中。然后你可以简单地做for item in mydict.items(): setupfile.write('%s = %s\n' % item)。或者更好的是,您可以使用json module 读取和写入整个dict

标签: python list text parameters write


【解决方案1】:

您可以参考answer 从变量中获取变量名。我在那里修改了namestr 函数以获取包含字母a 的变量名。这是因为其中的names变量包含['a1', 'name', '_96', '_97', '_134']等值

另外最好在打开文件时使用with,因为它会在工作完成后关闭。

a1,a2,a3,a4 = 3,5,10,15

def namestr(obj, namespace):
    names = [name for name in namespace if namespace[name] is obj]
    name = [n for n in names if 'a' in n]
    return name[0]

with open("setupfile.txt","w") as setupfile:
    x = [a1,a2,a4]
    for name in x:
        setupfile.write(namestr(name, globals()) + "=" + repr(name) +"\n")
    setupfile.close()

【讨论】:

  • 非常感谢您!我以前看过另一个答案,但没有意识到它适合我的问题
【解决方案2】:

我想出了一个不同的解决方案,它允许我拥有具有相同值的不同变量。 如果有人正在寻找相同的答案,您可以在这里找到它:creating txt file containing variablenames as string plus value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多