python ftp upload files and folders

Reference link: Python FTP

Where session = session = ftplib.FTP(host=”,user=”,passwd=”)

def upload_dir(path_source, session, target_dir=None):
 files = os.listdir(path_source)
 # Remember which working directory you were in
 last_dir = os.path.abspath('.')
 # Then switch to the target working directory
 os.chdir(path_source)if target_dir:
  current_dir = session.pwd()try:
   session.mkd(target_dir)
  except Exception:
   pass
  finally:
   session.cwd(os.path.join(current_dir, target_dir))for file_name in files:
  current_dir = session.pwd()if os.path.isfile(path_source + r'/{}'.format(file_name)):upload_file(path_source, file_name, session)
  elif os.path.isdir(path_source + r'/{}'.format(file_name)):
   current_dir = session.pwd()try:
    session.mkd(file_name)
   except:
    pass
   session.cwd("%s/%s"%(current_dir, file_name))upload_dir(path_source + r'/{}'.format(file_name), session)
  # The previous path may have changed, and you need to revert to the previous path
  session.cwd(current_dir)
 os.chdir(last_dir)
def upload_file(path, file_name, session, target_dir=None, callback=None):
 # Record the current ftp path
 cur_dir = session.pwd()if target_dir:try:
   session.mkd(target_dir)
  except:
   pass
  finally:
   session.cwd(os.path.join(cur_dir, target_dir))print("path:%s \r\n\t   file_name:%s"%(path, file_name))
 file =open(os.path.join(path, file_name),'rb')  # file to send
 session.storbinary('STOR %s'% file_name, file, callback = callback)  # send the file
 file.close()  # close file
 session.cwd(cur_dir)

Recommended Posts

python ftp upload files and folders
Python implements FTP to upload files in a loop
Python reads and writes json files
Python renames files
Python and Go
How to delete files and directories in python
How to read and write files with Python
[python] python2 and python3 under ubuntu
Python deconstruction and packaging
Python3 configuration and entry.md
Python automated operation and maintenance 2
Python introduction and environment installation
Python know crawler and anti crawler
centos7 install python3 and ipython
ubuntu18.04 compile and install python3.8
Python reads files by line
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python tornado upload file function
Python automated operation and maintenance 1
Python data structure and algorithm
Python multi-process and multi-thread basics
How Python implements FTP function
CentOS 6.9 compile and install python
python batch run py files
3 ways to encrypt Python files
CentOS 6 compile and install python 3
Generators and iterators in Python