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)
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)
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 thefor
about the objectdirs
. Make sure that the names of the two objects are equal so that the code works as expected.
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 python python-3.x
You are not signed in. Login or sign up in order to post.
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
– Fujimoto
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 withos.remove
.– Woss