Python-FTP下载目录中的所有文件 [英] Python-FTP download all files in directory
问题描述
from ftplib import FTP
import os,sys,os.path
def handleDownload(block):
file.write (块)
print。,
ddir ='C:\\Data\\test\\'
os.chdir(ddir)
ftp = FTP('test1 / server /')
print'登录'。
ftp.login('user1\\\\anon','pswrd20')
directory ='\\data\\test\\'
print'更改为'+目录
ftp.cwd(目录)
ftp.retrlines('LIST')
print'访问文件'
用于os.walk(目录)中的子目录,目录,文件:
用于文件在文件中:
full_fname = os.path.join(root,fname);
print'打开本地文件'
ftp.retrbinary('RETR C:\\Data\\test\\\''+ fname,
handleDownload,
打开(full_fname,'wb'));
print'关闭文件'+文件名
file.close();
ftp.close()
我敢打赌,你可以告诉它,我运行它,所以任何改进建议将不胜感激
PS这不是作业:DD
感谢!!
我已经设法解决这个问题,所以现在发布相关代码给未来的访问者: p>
filenames = ftp.nlst()#在目录中获取文件名
打印文件名
文件名中的文件名:
local_filename = os.path.join('C:\\test\\',filename)
file = open(local_filename,'wb')
ftp.retrbinary('RETR'+ filename,file.write)
file.close()
ftp.quit()#这是礼貌的关闭方式一个连接
这适用于Python 2.5,Windows XP中的我。
Python newb here so please bear with me. I m putting together a script to download all the files from a directory via FTP. So far I have managed to connect and fetch one file, but I cannot seem to make to work in batch (get all the files from the directory) Here is what I have so far:
from ftplib import FTP
import os, sys, os.path
def handleDownload(block):
file.write(block)
print ".",
ddir='C:\\Data\\test\\'
os.chdir(ddir)
ftp = FTP('test1/server/')
print 'Logging in.'
ftp.login('user1\\anon', 'pswrd20')
directory = '\\data\\test\\'
print 'Changing to ' + directory
ftp.cwd(directory)
ftp.retrlines('LIST')
print 'Accessing files'
for subdir, dirs, files in os.walk(directory):
for file in files:
full_fname = os.path.join(root, fname);
print 'Opening local file '
ftp.retrbinary('RETR C:\\Data\\test\\' + fname,
handleDownload,
open(full_fname, 'wb'));
print 'Closing file ' + filename
file.close();
ftp.close()
I bet you can tell that it does not do much when I run it, so any suggestions for improvements would be greatly appreciated
PS This is not homework :DD
Thanks!!
I've managed to crack this, so now posting the relevant bit of code for future visitors:
filenames = ftp.nlst() # get filenames within the directory
print filenames
for filename in filenames:
local_filename = os.path.join('C:\\test\\', filename)
file = open(local_filename, 'wb')
ftp.retrbinary('RETR '+ filename, file.write)
file.close()
ftp.quit() # This is the "polite" way to close a connection
This worked for me on Python 2.5, Windows XP.
这篇关于Python-FTP下载目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!