首页 > 解决方案 > 使用 Python ftplib 将文件夹中的文件上传到 FTP

问题描述

我正在尝试上传包含在单个目录中的一堆文件。

该代码没有失败,但似乎也不起作用。

到目前为止,我的代码如下:

import ftplib

FTP_HOST = "host"
FTP_USER = "user"
FTP_PASS = "pass"

ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)
ftp.encoding = "utf-8"

dirFTP = "dirPath"
toFTP = os.listdir(dirFTP)

for filename in toFTP:
    filePath = os.path.join(dirFTP, filename)
    with open(filePath, "rb") as file:
        ftp.storbinary(f"STOR {filePath}", file)

ftp.quit()

我在哪里做错了?

提前致谢。

标签: pythonftpuploadftplib

解决方案


好的。我的代码工作正常。

代码是:

import ftplib

FTP_HOST = "host"
FTP_USER = "user"
FTP_PASS = "pass"

ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)
ftp.encoding = "utf-8"

dirFTP = "dirPath"
toFTP = os.listdir(dirFTP)

for filename in toFTP:
    with open(os.path.join(dirFTP,filename), 'rb') as file:  #Here I open the file using it's  full path
        ftp.storbinary(f'STOR {filename}', file)  #Here I store the file in the FTP using only it's name as I intended

ftp.quit()

谢谢您的帮助。


推荐阅读