FTP upload files Python

后端 未结 4 1856
星月不相逢
星月不相逢 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

    Combined both suggestions. Final answer being

    #!/usr/bin/python
    import ftplib
    import os
    filename = "MyFile.py"
    ftp = ftplib.FTP("xx.xx.xx.xx")
    ftp.login("UID", "PSW")
    ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
    os.chdir(r"\\windows\folder\which\has\file")
    myfile = open(filename, 'r')
    ftp.storlines('STOR ' + filename, myfile)
    myfile.close()
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-31 22:09

    If you are trying to store a non-binary file (like a text file) try setting it to read mode instead of write mode.

    ftp.storlines("STOR " + filename, open(filename, 'rb'))
    

    for a binary file (anything that cannot be opened in a text editor) open your file in read-binary mode

    ftp.storbinary("STOR " + filename, open(filename, 'rb'))
    

    also if you plan on using the ftp lib you should probably go through a tutorial, I'd recommend this article from effbot.

    0 讨论(0)
  • 2021-01-31 22:12

    try making the file an object, so you can close it at the end of the operaton.

    myfile = open(filename, 'w')
    ftp.storbinary('RETR %s' % filename, myfile.write)
    

    and at the end of the transfer

     myfile.close()
    

    this might not solve the problem, but it may help.

    0 讨论(0)
提交回复
热议问题