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)
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)
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 executesfor
on thedirs
object. Make sure the names of the two objects are the same so that the code works as expected.
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')