简体   繁体   English

如何制作Python脚本以从FTP服务器下载文件

[英]How to make a Python script to download a file from a FTP server

I am trying to download a file from my FTP server to a specific folder, without a GUI. 我正在尝试从FTP服务器将文件下载到没有GUI的特定文件夹。 This is what I have so far, but it does nothing, 到目前为止,这就是我所拥有的,但是它什么也没做,

import urllib
urllib.urlretrieve('ftp://USERNAME:PASSWORD@ftp.SERVERNAME/File path/', 'FILENAME')

I edited my answer to be more simpler ..now we will need to use FtpLib 我将答案编辑得更简单..现在我们将需要使用FtpLib

the code below is straightforward and it's elegant :D 下面的代码简单明了:D

import ftplib

path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'

ftp = ftplib.FTP("Server IP") 
ftp.login("UserName", "Password") 
ftp.cwd(path)
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()

Just in case you need some explanation: 万一您需要一些解释:

path is obviously the location of the file in the ftp server 路径显然是ftp服务器中文件的位置

filename is the name + extension of the file you want to download form server filename是您要下载表单服务器的文件的名称+扩展名

ftp.login is where you'll put your credentials(username, password) ftp.login是您放置凭据(用户名,密码)的地方

ftp.cwd will change the current working directory to where the file is located in order to download it :) ftp.cwd会将当前工作目录更改为文件所在的目录,以便下载它:)

retrbinary simply will get the file from the server and store in your local machine using the same name it had on the server :) retrbinary只会从服务器获取文件,并使用与服务器上相同的名称存储在本地计算机中:)

Do not forget to change Server IP argument to your server's ip 不要忘记将服务器IP参数更改为服务器的ip

and Voila that's it. 瞧,就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM