如何从python将变量导出到.txt文件

时间:2018-01-04 15:42:15

标签: python

这是我的程序中的一个功能:

def display_ap():
    global var_set
    global var_requestedby
    global var_content
    global var_due
    global var_ap_set
    if var_ap_set == True:
        print("[***]\n")
        print("Set:  "+ str(var_set)+"\n")
        print("Requested by:  "+ str(var_requestedby)+"\n")
        print("Content:  "+ str(var_content)+"\n")
        print("Due:  "+ str(var_due)+"\n")
        print("have values have been set correctly? - "+ str(var_ap_set)+"\n")
        print("values have been set correctly; list ready to generate")

我需要将var_set,var_requestedby,var_content和var_due按顺序导出到.txt文件,一个在另一个上面。我将如何编写程序的导出函数部分。

2 个答案:

答案 0 :(得分:0)

我建议通过传递字典来使用Python字符串格式。然后,您可以在{}中的文本中指定全局变量,并按如下方式传递globals()字典:

def display_ap():
    if var_ap_set == True:

        text = """[***]
Set:  {var_set}
Requested by:  {var_requestedby}
Content:  {var_content}
Due:  {var_due}
have values have been set correctly? - {var_ap_set}
values have been set correctly; list ready to generate""".format(**globals())

        print(text)

        with open('output.txt', 'w') as f_output:
            f_output.write(text)

display_ap()        

答案 1 :(得分:0)

最好改用writelines函数。您需要编写的函数应如下所示:

def save_to_file():
global var_set
global var_requestedby
global var_content
global var_due
global var_ap_set

fullpath = r'You Path + Filename Here'
with open(fullpath, "w") as f:
    f.writelines(f"[***]\n")
    f.writelines(f"Set:  "+ str(var_set)+"\n")
    f.writelines(f"Requested by:  "+ str(var_requestedby)+"\n")
    f.writelines(f"Content:  "+ str(var_content)+"\n")
    f.writelines(f"Due:  "+ str(var_due)+"\n")
    f.writelines(f"have values have been set correctly? - "+ str(var_ap_set)+"\n")
    f.writelines(f"values have been set correctly; list ready to generate\n")

那是从您的印刷声明中写的。但是,如果要直接输出变量值,可以使用格式化字符串,其功能如下:

def save_to_file():
global var_set
global var_requestedby
global var_content
global var_due
global var_ap_set

fullpath = r'You Path + Filename Here'
with open(fullpath, "w") as f:
    f.writelines(f"var_set: {var_set}\n")
    f.writelines(f"var_requestedby: {var_requestedby}\n")
    f.writelines(f"var_content: {var_content}\n")
    f.writelines(f"var_due: {var_due}\n")
    f.writelines(f"var_ap_set: {var_ap_set}\n")