嗨,我尝试建立一个脚本,从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\\..'发布于 2015-03-18 01:16:03
它试图访问的filename是..,它是“上一个目录”。您正在尝试创建一个名为D:\\test\\..的文件,该文件实际上是D:\\。你不能创建这样的文件,所以你会得到一个“权限被拒绝”的错误。
ftp.nlst()的操作类似于Unix ls命令,因为它返回两个“隐含文件”:
..:the parent directory.:the current directory(为当前目录创建父目录)
您可能希望更新代码以过滤掉这些内容。
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'发布于 2015-03-18 01:16:32
文件列表中包含父文件夹的..。你必须跳过这一步。D:\test\..是D:\。
发布于 2015-03-18 01:52:52
谢谢,它的效果好多了一点。
我尝试将文件1.txt复制到8.txt,它现在在"D:\test“中创建了1.txt,但文件中没有任何内容
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'https://stackoverflow.com/questions/29105467
复制相似问题