7

当前代码会将远程 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()
4

2 回答 2

7

使用os.chdir()更改本地工作目录,然后在获取文件后将其更改回来。

我已经用 a 标记了添加的行####

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()
于 2013-04-08T07:33:31.930 回答
6

ftplib 的默认行为是将所有文件从服务器复制到当前工作目录 (CWD)。

要指定文件的位置,您可以临时修改 CWD 使用os.chdir(),您可以使用找到当前 CWDos.getcwd()


使用示例:

>>> import os
>>> os.getcwd()
'C:\\python'
>>> tmp_a = os.getcwd()
>>> os.chdir('C:/temp')
>>> os.getcwd()
'C:\\temp'
>>> os.chdir(tmp_a)
>>> os.getcwd()
'C:\\python'
于 2013-04-08T07:43:48.483 回答