当前代码会将远程 XML 文件下载到该程序所在的目录。 如何指定另一个本地目录作为目的地?
如果这里有什么奇怪的代码也请指出。 :)
import ftplib
import os
import os
import socket
HOST = 'ftp.server.com'
DIRN = 'DirectoryInFTPServer'
filematch = '*.xml'
username = 'username'
password = 'password'
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
print 'ERROR: cannot reach "%s"' % HOST
return
print '*** Connected to host "%s"' % HOST
try:
f.login(username, password)
except ftplib.error_perm, e:
print 'ERROR: cannot login'
f.quit
return
print '*** Logged in successfully'
try:
f.cwd(DIRN)
except ftplib.error_perm, e:
print 'ERROR: cannot CD to "%s"' % DIRN
f.quit()
print '*** Changed to folder: "%s"' % DIRN
try:
s = 0;
for filename in f.nlst(filematch):
fhandle = open(filename, 'wb')
print 'Getting ' + filename
f.retrbinary('RETR ' + filename, fhandle.write)
s = s + 1
except ftplib.error_perm, e:
print 'ERROR: cannot read file "%s"' % filename
os.unlink(filename)
f.quit()
print 'Files downloaded: ' + str(s)
return
if __name__ == '__main__':
main()
最佳答案
使用os.chdir()更改本地工作目录,然后在获取文件后将其更改回来。
我用####
标记了添加的行
import ftplib
import os
import os
import socket
HOST = 'ftp.server.com'
DIRN = 'DirectoryInFTPServer'
filematch = '*.xml'
username = 'username'
password = 'password'
storetodir='DirectoryToStoreFilesIn' ####
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
print 'ERROR: cannot reach "%s"' % HOST
return
print '*** Connected to host "%s"' % HOST
try:
f.login(username, password)
except ftplib.error_perm, e:
print 'ERROR: cannot login'
f.quit
return
print '*** Logged in successfully'
try:
f.cwd(DIRN)
except ftplib.error_perm, e:
print 'ERROR: cannot CD to "%s"' % DIRN
f.quit()
print '*** Changed to folder: "%s"' % DIRN
currdir=os.getcwd() ####
try:
os.chdir(storetodir)####
s = 0;
for filename in f.nlst(filematch):
fhandle = open(filename, 'wb')
print 'Getting ' + filename
f.retrbinary('RETR ' + filename, fhandle.write)
s = s + 1
except ftplib.error_perm, e:
print 'ERROR: cannot read file "%s"' % filename
os.unlink(filename)
os.chdir(currdir) ####
f.quit()
print 'Files downloaded: ' + str(s)
return
if __name__ == '__main__':
main()
关于python - 从 FTP 检索文件时如何指定本地目标文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15873427/