简体   繁体   中英

How to export variables to a .txt file from python

This is a function from my program:

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")

I need var_set, var_requestedby, var_content and var_due to be exported to a .txt file in that order, one on top of the other. how would I go about writing the export function part of the program.

I would suggest using Python string formatting by passing a dictionary. You can then specify the global variables in the text within {} and pass the globals() dictionary as follows:

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()        

Better use writelines function instead. The function you need to write should be as follows:

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")

That was written from your print statements. But if you want to directly output the variable values, we can make use of formatted-strings, function below:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM