Python 从FTP检索文件时如何指定本地目标文件夹
当前代码将远程XML文件下载到此程序所在的目录。 如何指定另一个本地目录作为目标 如果这里有任何奇怪的代码,也请告诉我。:) 用于更改本地工作目录,然后在获取文件后将其更改回 我已经用Python 从FTP检索文件时如何指定本地目标文件夹,python,python-2.7,ftp,Python,Python 2.7,Ftp,当前代码将远程XML文件下载到此程序所在的目录。 如何指定另一个本地目录作为目标 如果这里有任何奇怪的代码,也请告诉我。:) 用于更改本地工作目录,然后在获取文件后将其更改回 我已经用#####标记了添加的行 ftplib的默认行为是将所有文件从服务器复制到当前工作目录(CWD) 要指定文件的位置,可以使用临时修改CWD,并使用查找当前CWD 使用示例: >>> import os >>> os.getcwd() 'C:\\python' >>&
#####
标记了添加的行
ftplib的默认行为是将所有文件从服务器复制到当前工作目录(CWD) 要指定文件的位置,可以使用临时修改CWD,并使用查找当前CWD
使用示例:
>>> 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'
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()
>>> 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'