FTP upload files Python

2020-05-19 03: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 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")
ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)

I am getting the following error:

Traceback (most recent call last):
  File "Windows\folder\which\has\file\MyFile.py", line 11, in <module>
    ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)
  File "windows\folder\Python\lib\ftplib.py", line 466, in storbinary
    buf = fp.read(blocksize)
AttributeError: 'builtin_function_or_method' object has no attribute 'read'

Also all contents of MyFile.py got deleted .

Can anyone advise what is going wrong.I have read that ftp.storbinary is used for uploading files using FTP.

回答1:

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, 'r'))

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.



回答2:

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()


回答3:

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.



回答4:

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



标签: python ftp