KorD WLO
KorD WLO

Reputation: 13

How to save screen output into a text file

So I need to create a script and save the info into a text file, and here is what I did:

import platform

def bios_version():
    uname_result = platform.uname()
    pl = {}
    pl['BIOS version'] = uname_result.version

    for a, b in pl.items():
        print(a, ":", b)

#The def is working perfectly but I don't know how to save the file.

print(bios_version())
save_path = 'D:/'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")

f = open(completeName, "w")
f.write(bios_version())
f.close

So it return:

f.write(bios_version())
TypeError: write() argument must be str, not None"

Upvotes: 1

Views: 431

Answers (2)

Niloct
Niloct

Reputation: 10015

Here's an alternative, considering other answers:

import platform
import os

def write_bios_version(file_name = None):
    pl = {}
    pl['BIOS version'] = platform.uname().version

    with open(file_name, 'w') as f:
        for a, b in pl.items():
            print(a, ":", b, file=f)

save_path = 'D:/'
name_of_file = input("What is the name of the file: ")
complete_name = os.path.join(save_path, name_of_file+".txt")
write_bios_version(complete_name)

Upvotes: 0

Akshay Jain
Akshay Jain

Reputation: 790

Try below code:

  • I don't understand why you are using loop and why to store that version detail in dictionary. If there is only single value then just store that in variable and directly return the value and just write into file.

Code

import platform
import os

def bios_version():
    uname_result = platform.uname()
    pl = f"BIOS version: {uname_result.version}"
    return pl

save_path = 'D:/'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")

f = open(completeName, "w")
f.write(bios_version())
f.close

Output:

BIOS version: <<Your version detail>>

Upvotes: 1

Related Questions