How do I delete a file from a python folder

Asked

Viewed 16,445 times

0

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

 def etc():
     path ="diretorio"`
     dir = os.listdir(path)
     for file in dirs:
         print(file)

2 answers

4


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

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 you find it in the directory.

Heed: in your code, you assign the list of files to the object dir, but executes the for about the object dirs. Make sure that the names of the two objects are equal so that the code works as expected.

  • in case I wanted to create as if it were an input() because after listed I could delete a specific, I don’t know if you understood me

  • Then I believe you can do it yourself from now on. Keep your code to list the files, request the user the name of the file that will be deleted with input and remove it with os.remove.

0

import the

def clean up():

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

Browser other questions tagged

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