FTP upload files Python

后端 未结 4 1854
星月不相逢
星月不相逢 2021-01-31 21:11

I am trying to upload file from windows server to a unix server (basically trying to do FTP). I have used the code below

#!/usr/bin/python
import ftplib
import          


        
4条回答
  •  失恋的感觉
    2021-01-31 21:56

    ftplib supports the use of context managers so you can make it even simpler as such

        with ftplib.FTP('ftp_address', 'user', 'pwd') as ftp, open(file_path, 'rb') as file:
            ftp.storbinary(f'STOR {file_path.name}', file)
            ...
    

    This way you are robust against both file and ftp issues without having to insert try/except/finally blocks. And well, it's pythonic.

    PS: since it uses f-strings is python >= 3.6 only but can easily be modified to use the old .format() syntax

提交回复
热议问题