Python: Error in . write() method

Asked

Viewed 67 times

-2

I wrote a code that would run on my Desktop. The script would write a text in another directory. To switch directories, I used os.chdir(), then used subprocess.check_output() to execute a shell command and list the files in my folder and the method. write() to write the entire list of files in a text file. Follow the code:

import subprocess
import os


dados = []

os.chdir(r'C:\Users\Usuário\Desktop\Teste')

retorno = str(subprocess.check_output(['dir'], shell=True))
dados.append(retorno)


arquivo = open('hello world.txt', 'a')
arquivo.write(dados[0])

The problem is in the line ".write(data[0])", apparently only because I changed the directory in os.chdir(), the . write() method no longer works. When running the program, the hello world.txt file is normally created in the directory I specified, but there is nothing written there. Does anyone know why this happens?

1 answer

1

The problem is that you are not closing the file in your program to make the changes. To close the file, use the method close() as in the code below.

arquivo = open('hello world.txt', 'a')
arquivo.write(dados[0])
arquivo.close()

You can also use the with for the file to be closed automatically.

with open('hello world.txt', 'a') as arquivo:
    arquivo.write(dados[0])

Browser other questions tagged

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