Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FTP upload files Python

Tags:

python

ftp

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.

like image 652
misguided Avatar asked Jul 03 '13 00:07

misguided


People also ask

How do you upload a file in Python?

Method 1: Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.


1 Answers

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.

like image 71
John Avatar answered Oct 07 '22 23:10

John