Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change directory on server before uploading files with ftplib in Python

Tags:

python

ftp

ftplib

I have this code, but I can't figure out how to change directory on the server before uploading files.

Can anyone help me out?

import ftplib
import os

server = 'enter your servername here'
username = 'root'
password = 'passowrd'
myFTP = ftplib.FTP(server, username, password)
myPath = r'C:\path_of_the_folder_goes_here'
def uploadThis(path):
    files = os.listdir(path)
    os.chdir(path)
    for f in files:
        if os.path.isfile(path + r'\{}'.format(f)):
            fh = open(f, 'rb')
            myFTP.storbinary('STOR %s' % f, fh)
            fh.close()
        elif os.path.isdir(path + r'\{}'.format(f)):
            myFTP.mkd(f)
            myFTP.cwd(f)
            uploadThis(path + r'\{}'.format(f))
    myFTP.cwd('..')
    os.chdir('..')
uploadThis(myPath)
like image 525
user3551620 Avatar asked May 01 '17 10:05

user3551620


People also ask

How do I change directory in FTP Python?

If I want I to change directory I would just use ftp. cwd(path) to do so. To close the FTP connection, use the quit() method.

What is Ftplib module in Python?

Source code: Lib/ftplib.py. This module defines the class FTP and a few related items. The FTP class implements the client side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers.


Video Answer


1 Answers

Use FTP.cwd method:

myFTP.cwd('/remote/path')

before you call

uploadThis(myPath)
like image 179
Martin Prikryl Avatar answered Oct 12 '22 11:10

Martin Prikryl