How do I delete a file from a folder in python

0

The code below lists the files of a certain directory, I wanted to know how do I delete only 1 file from this directory

 def etc():
     path ="diretorio"'
     dir = os.listdir(path)
     for file in dirs:
         print(file)
    
asked by anonymous 28.04.2017 / 04:01

2 answers

3

To remove a file, you can use the os.remove(path) function:

import os

def etc():
    path = "diretorio"'
    dir = os.listdir(path)
    for file in dir:
        if file == "arquivo.txt":
            os.remove(file)

The above example deletes the file arquivo.txt if it finds it in the directory.

  

Warning : In your code, you assign the list of files to the dir object, but it executes for on the dirs object. Make sure the names of the two objects are the same so that the code works as expected.

    
28.04.2017 / 04:13
0
  

import them

     

def clean ():

pasta = "diretorio"
arquivo = str(input('digite o nome do arquivo que deseja apagar: '))
diretorio = os.listdir(pasta)
if arquivo in diretorio:
    print('---removendo arquivo----')
    os.remove('{}/{}'.format(pasta, arquivo))
    print('%s removido da pasta %s' % (pasta, arquivo))
else:
    print('este arquivo nao existe')
    
18.08.2017 / 19:30