How to save the output result of a Python script to a txt file?

Asked

Viewed 5,733 times

0

Script showing saved wifi passwords:

import subprocess
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors="backslashreplace").split('\n')
profiles = [i.split(":") [1] [1:-1] for i in data if "Todos os Perfis de Usu\\xa0rios" in i]
for i in profiles:
    try:
        results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8', errors="backslashreplace).split('\n')
        results = [b.split(":") [1] [1:-1] for b in results if "Conte\\xa3do da Chave" in b]
        try:
            print ("{:<30}|  {:<}".format(i, results[0]))
        except IndexError:
            print ("{:<30}|  {:<}".format(i, "")
    except subprocess.CalledProcessError:
        print ("{:<30}|  {:<}".format(i, "ENCODING ERROR"))
input("")

Output: Saída

To save the output result in a TXT document without having to show the PRINT in "Shell"?

3 answers

1

Just like in previous responses, you can save the result by opening a file and writing the output to it.

with open('nomeDoArquivo.txt', 'w') as arquivo:
    # <Seu código aqui>
    print('Sua saída', file=arquivo)

Using this syntax, it is not necessary to close the file after use, this will be done automatically.

But it is also possible to modify the output of the system without modifying its algorithm, by redirecting the default output of its operating system.

To do this, just run the following command on the terminal:

python your.py > filename.txt

Your program will work in the same way as before, except that its default output is now the "filename.txt" file instead of the terminal screen

0

vc opens an open file using the 'w' flag, and vc can make a change to the print to send the information to the archive instead of the terminal

arquivo = open('arquivo.txt', 'w')
print('informação', file=arquivo) 
arquivo.close()

if you have difficulty changing the print, you can use the file’s own writing method

arquivo.write('informação')

0

To write to a file, just the following code:

file = open('file.txt', 'w')
file.write('Seu texto aqui')
file.close()

Remembering that in the code above, the argument 'w' overwritten everything in . txt

To add files without overwriting the content . txt already has, we use the argument append in form:

file = open('file.txt', 'a')
file.write('Seu texto aqui')
file.close()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.