'Delete all files and folders after connecting to FTP
I want to connect through FTP to an address and then delete all contents. Currently I am using this code:
from ftplib import FTP
import shutil
import os
ftp = FTP('xxx.xxx.xxx.xxx')
ftp.login("admin", "admin")
for ftpfile in ftp.nlst():
if os.path.isdir(ftpfile)== True:
shutil.rmtree(ftpfile)
else:
os.remove(ftpfile)
My problem is I always get this error when he is trying to delete the first file:
os.remove(ftpfile)
WindowsError: [Error 2] The system cannot find the file specified: somefile.sys
Anyone has an idea why?
Solution 1:[1]
for something in ftp.nlst():
try:
ftp.delete(something)
except Exception:
ftp.rmd(something)
Any other ways?
Solution 2:[2]
This function deletes any given path recursively:
# python 3.6
from ftplib import FTP
def remove_ftp_dir(ftp, path):
for (name, properties) in ftp.mlsd(path=path):
if name in ['.', '..']:
continue
elif properties['type'] == 'file':
ftp.delete(f"{path}/{name}")
elif properties['type'] == 'dir':
remove_ftp_dir(ftp, f"{path}/{name}")
ftp.rmd(path)
ftp = FTP(HOST, USER, PASS)
remove_ftp_dir(ftp, 'path_to_remove')
Solution 3:[3]
from ftplib import FTP
import shutil
import os
ftp = FTP("hostname")
ftp.login("username", "password")
def deletedir(dirname):
ftp.cwd(dirname)
print(dirname)
for file in ftp.nlst():
try:
ftp.delete(file)
except Exception:
deletedir(file)
ftp.cwd("..")
ftp.rmd(dirname)
for ftpfile in ftp.nlst():
try:
ftp.delete(ftpfile)
except Exception:
deletedir(ftpfile)
Solution 4:[4]
ftp.nlst()
The above statement returns a list of file names.
os.remove()
The above statement requires a file path.
Solution 5:[5]
from ftplib import FTP
#--------------------------------------------------
class FTPCommunicator():
def __init__(self):
self.ftp = FTP()
self.ftp.connect('server', port=21, timeout=30)
self.ftp.login(user="user", passwd="password")
def getDirListing(self, dirName):
listing = self.ftp.nlst(dirName)
# If listed a file, return.
if len(listing) == 1 and listing[0] == dirName:
return []
subListing = []
for entry in listing:
subListing += self.getDirListing(entry)
listing += subListing
return listing
def removeDir(self, dirName):
listing = self.getDirListing(dirName)
# Longest path first for deletion of sub directories first.
listing.sort(key=lambda k: len(k), reverse=True)
# Delete files first.
for entry in listing:
try:
self.ftp.delete(entry)
except:
pass
# Delete empty directories.
for entry in listing:
try:
self.ftp.rmd(entry)
except:
pass
self.ftp.rmd(dirName)
def quit(self):
self.ftp.quit()
#--------------------------------------------------
def main():
ftp = FTPCommunicator()
ftp.removeDir("/Untitled")
ftp.quit()
#--------------------------------------------------
if __name__ == "__main__":
main()
#--------------------------------------------------
Solution 6:[6]
@Dmytro Gierman has the best option in my opinion, however, I don't want to delete the main folder, only the subfolder and all files inside. Here is a script in order to make it work
import ftplib
# python 3.9
def remove_ftp_dir(ftp, path, mainpath):
for (name, properties) in ftp.mlsd(path=path):
if name in ['.', '..']:
continue
elif properties['type'] == 'file':
ftp.delete(f"{path}/{name}")
elif properties['type'] == 'dir':
remove_ftp_dir(ftp, f"{path}/{name}", mainpath)
if path != mainpath: #only deletes subdirectories not he mainpath
ftp.rmd(path)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Prikryl |
| Solution 2 | Dmytro Gierman |
| Solution 3 | Flavia Giammarino |
| Solution 4 | pravin |
| Solution 5 | |
| Solution 6 | Miller Bento |
