删除 Python 中 FTP 文件夹中的所有文件失败并显示“500 无效命令:"MLSD"”
Deleting all files in FTP folder in Python fails with "500 Invalid command: "MLSD""
我正在尝试使用带 Python 的 ftplib 删除文件夹。
我试过 ftp.delete
,但它只接受文件
我试过 ftp.rmd
但这只适用于空文件夹。
试了一个网上找的递归函数:
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.mlsd
时,我得到:
ftplib.error_perm: 500 Invalid command: "MLSD"
为了将来每个人都需要这个,我写了一个删除功能,可以在每个服务器上运行:
def delete_dir (ftp , deleteDirPath):
ftp.cwd(deleteDirPath)
print("Current wd --- " , ftp.pwd())
contents =ftp.nlst(deleteDirPath)
# if empty dir - delete it
try:
ftp.rmd(deleteDirPath)
except error_perm as e:
if not e.args[0].startswith("550"):
raise
# loop on all folder objects list
for name in contents:
try:
# delete if file
print(deleteDirPath + "/" + name)
ftp.delete( deleteDirPath + "/" + name)
#time.sleep(0.7)
print("Succeed delete = ", deleteDirPath + "/" + name)
except:
# if folder
delete_dir(ftp ,deleteDirPath + "/" + name)
# if empty dir - delete it
try:
ftp.rmd(deleteDirPath)
except error_perm as e:
if not e.args[0].startswith("550"):
raise
我正在尝试使用带 Python 的 ftplib 删除文件夹。
我试过 ftp.delete
,但它只接受文件
我试过 ftp.rmd
但这只适用于空文件夹。
试了一个网上找的递归函数:
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.mlsd
时,我得到:
ftplib.error_perm: 500 Invalid command: "MLSD"
为了将来每个人都需要这个,我写了一个删除功能,可以在每个服务器上运行:
def delete_dir (ftp , deleteDirPath):
ftp.cwd(deleteDirPath)
print("Current wd --- " , ftp.pwd())
contents =ftp.nlst(deleteDirPath)
# if empty dir - delete it
try:
ftp.rmd(deleteDirPath)
except error_perm as e:
if not e.args[0].startswith("550"):
raise
# loop on all folder objects list
for name in contents:
try:
# delete if file
print(deleteDirPath + "/" + name)
ftp.delete( deleteDirPath + "/" + name)
#time.sleep(0.7)
print("Succeed delete = ", deleteDirPath + "/" + name)
except:
# if folder
delete_dir(ftp ,deleteDirPath + "/" + name)
# if empty dir - delete it
try:
ftp.rmd(deleteDirPath)
except error_perm as e:
if not e.args[0].startswith("550"):
raise