Python:ftplib和os Errno13(从ftp服务器下载所有文件)

时间:2015-03-17 17:11:33

标签: python ftp errno ftplib

您好我尝试构建一个脚本,将所有文件从ftp服务器下载到我的硬盘并在ftp文件夹中删除它们。

这是代码。

from ftplib import FTP
import os
ftp = FTP('ftp.server.xxx')
ftp.login(user='user', passwd = 'pass')
ftp.cwd('/subfolder1/')
ftp.retrlines('LIST')
filenames = ftp.nlst()
print filenames

for filename in filenames:
    local_filename = os.path.join('D:\\test\\', filename)
    file = open(local_filename, 'wb')
    ftp.retrbinary('RETR '+ filename, file.write)
    ##here i want to delete the file and then Switch to the next file

ftp.quit()

print 'Finished'

问题是我得到了这个错误。文件夹" D:\ Temp"存在

Traceback (most recent call last):
  File "C:/Python27/test2.py", line 12, in <module>
    file = open(local_filename, 'wb')
IOError: [Errno 13] Permission denied: 'D:\\test\\..'

3 个答案:

答案 0 :(得分:1)

它尝试访问的filename..,即“一个目录”。您正在尝试创建名为D:\\test\\..的文件,该文件实际上是D:\\。您无法创建此类文件,因此您收到“权限被拒绝”错误。

ftp.nlst()的操作类似于Unix ls命令,因为它返回两个“隐含文件”:

  • ..:父目录
  • .:当前目录

您可能希望更新代码以过滤掉这些代码。

from ftplib import FTP
import os
ftp = FTP('ftp.server.xxx')
ftp.login(user='user', passwd = 'pass')
ftp.cwd('/subfolder1/')
ftp.retrlines('LIST')
filenames = ftp.nlst()
print filenames

for filename in filenames:
    if filename not in ['..', '.']:
        local_filename = os.path.join('D:\\test\\', filename)
        file = open(local_filename, 'wb')
        ftp.retrbinary('RETR '+ filename, file.write)
        ##here i want to delete the file and then Switch to the next file

ftp.quit()

print 'Finished'

答案 1 :(得分:0)

文件列表包含父文件夹的..。你必须跳过它。 D:\test\..D:\

答案 2 :(得分:0)

谢谢你的工作多了一点。

我尝试将文件1.txt复制到8.txt 它创建了1.txtin&#34; D:\ test&#34;现在但文件中没有任何内容

drwxr-x---   9 ftp      ftp          4096 Mar 17 17:32 ..
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 1.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 2.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 3.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 4.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 5.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 6.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 7.txt
-rw-r--r--   1 ftp      ftp             7 Mar 17 17:37 8.txt
['..', '1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt', '8.txt']

Traceback (most recent call last):
  File "C:/Python27/test2.py", line 14, in <module>
    ftp.retrbinary('RETR '+ filename, file.write)
  File "C:\Python27\lib\ftplib.py", line 398, in retrbinary
    self.voidcmd('TYPE I')
  File "C:\Python27\lib\ftplib.py", line 248, in voidcmd
    self.putcmd(cmd)
  File "C:\Python27\lib\ftplib.py", line 178, in putcmd
    self.putline(line)
  File "C:\Python27\lib\ftplib.py", line 173, in putline
    self.sock.sendall(line)
AttributeError: 'NoneType' object has no attribute 'sendall'