这是一个菜鸟的问题~~ 虚心求教python大虾~~
大虾们 我要从远端下载某个文件夹内的数据到本地应该怎么写 求用代码示例说明下诶 谢大虾们了~~~
这是一个菜鸟的悲哀~~
[解决办法]
首先你要确定你的下载方式 SSH FTP HTTP Socket ??
然后再说python用什么方式可以实现
[解决办法]
贴一个ftplib简单的使用示例:
'''
a mini ftp client
'''
from ftplib import FTP,all_errors
from ftpc_cfg import *
#print usage
def help():
with open('helptxt','r') as f:
for line in f:print line
#list files function ,with closure...........
def list_files(ftp):
index = [0]
ftpfiles=[]
def list_files_callback(line):
print index[0],line
index[0]=index[0]+1
ftpfiles.append(line[line.rfind(' ')+1:])
ftp.retrlines('LIST',list_files_callback)
return ftpfiles
#run time cmd
def rt_cmd(ftpinstance,current_path,files):
cur_path = current_path
cur_files = files
ftp = ftpinstance
def down_callback(data):
pass
while True:
print 50*'*'
print ' cd@id: change server directory, e.g. cd@0'
print ' get@id: download file , e.g. get@2'
print ' put@localfile: upload a local file'
print ' q/Q to exit.'
print 50*'*'
cmd = raw_input('>>>')
if cmd=='q' or cmd=='Q':
break
if cmd[:3]=='cd@':
index=0
try:index=int(cmd[cmd.rfind('@')+1:])
except BaseException,e:
print 'error:',e
else:
try:
ftp.cwd(cur_files[index])
cur_files=list_files(ftp)
except (all_errors,BaseException),e:
print 'error:',e
if cmd[:4]=='get@':
index=0
try:index=int(cmd[cmd.rfind('@')+1:])
except BaseException,e:
print 'error:',e
else:
with open(DOWNPATH+cur_files[index],'wb') as f:
try:
ftp.retrbinary('RETR '+cur_files[index],f.write)
except (all_errors,BaseException),e:
print 'error:',e
else:
print 'get',cur_files[index],'done'
if cmd[:4]=='put@':
localfile=''
localfile=cmd[cmd.rfind('@')+1:]
with open(localfile,'rb') as f:
try:
ftp.storbinary('STOR '+localfile[localfile.rfind('\\')+1:],f)
except (all_errors,BaseException),e:
print 'error:',e
else:
print 'put',localfile,'done'
def ftp_client_entry():
try:
#login
ftp=FTP()
ftp.connect(HOST,21,60)
ftp.login(USER,PWD)
#enter root directory
print ftp.getwelcome()
ftpfiles=list_files(ftp)
#runtime cmd
rt_cmd(ftp,HOST+'/',ftpfiles)
#clean up
ftp.quit()
ftp.close()
except all_errors,e:
print 'error:',e
finally:
print 'exitting..........'
if __name__ == '__main__':
help()
ftp_client_entry()