Python - Uploading Data


Advertisements

We can upload data to a serer using python's module which handle ftp or File Transfer Protocol.

We need to install the module ftplib to acheive this.

pip install ftplib

Using ftplib

In the below example we use FTP method to connect to the server and then supply the user credentials. Next we mention the name of the file and the storbinary method to send and store the file in the server.

import ftplib

ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "password")
file = open('index.html','rb')   
ftp.storbinary("STOR " + file, open(file, "rb"))
file.close()                                   
ftp.quit() 

When we run the above program, we observer that a copy of the file has been created in the server.

Using ftpreety

Similar to ftplib we can use ftpreety to connect securely to a remote server and upload file. We can aslo download file using ftpreety. The below program illustraits the same.


from ftpretty import ftpretty

# Mention the host
host = "127.0.0.1"

# Supply the credentisals
f = ftpretty(host, user, pass )

# Get a file, save it locally
f.get('someremote/file/on/server.txt', '/tmp/localcopy/server.txt')

# Put a local file to a remote location
# non-existent subdirectories will be created automatically
f.put('/tmp/localcopy/data.txt', 'someremote/file/on/server.txt')

When we run the above program, we observer that a copy of the file has been created in the server.

Advertisements