#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2023/06/19 03:00:15 +0900> """ FTP client example. Windows10 x64 22H2 + Python 3.10.10 64bit """ import os import ftplib IP_ADDRESS = "127.0.0.1" USER = "user" PASSWORD = "password" files = [ ["D:\\home\\prg\\python\\_test_sample\\ftp\\src\\index.html", "/public_html/2_natsu"], ["D:\\home\\prg\\python\\_test_sample\\ftp\\src\\b.png", "/public_html/2_natsu"], ] asciimode_ext = ["html", "htm", "css", "cgi", "pl", "py", "rb", "php", "js"] try: ftp = ftplib.FTP(IP_ADDRESS) ftp.set_pasv('true') ftp.login(USER, PASSWORD) print("# FTP login (%s@%s)" % (USER, IP_ADDRESS)) print(ftp.getwelcome()) # get file list print(ftp.nlst(".")) print(ftp.nlst("./public_html")) for d in files: src, dst = d if not os.path.isfile(src): print("Error : Not found %s" % src) continue ftp.cwd(dst) fn = os.path.basename(src) ext = os.path.splitext(src)[1][1:] if ext in asciimode_ext: print("Upload (Ascii) %s -> %s/%s" % (src, dst, fn)) # ftp.voidcmd('TYPE A') with open(src, "rb") as f: ftp.storlines("STOR %s" % fn, f) else: print("Upload (Binary) %s -> %s/%s" % (src, dst, fn)) # ftp.voidcmd('TYPE I') with open(src, "rb") as f: ftp.storbinary("STOR %s" % fn, f) ftp.quit() # ftp.close() print("# FTP close.") except ftplib.all_errors as e: print('FTP Error :', e)