Home > other >  How to put FTP file into a certain map
How to put FTP file into a certain map

Time:05-17

remotefile=f'{fileName}'
with open(remotefile, "rb") as file:
    ftp.storbinary('STOR %s' % remotefile, file)

How to put the file into a certain map?

CodePudding user response:

If you mean to put in folder/directory then you can do one of two things

  1. change remote folder before STOR
localfile  = 'test/input.txt'

remotefile = 'output.txt'

ftp.cwd('folder1/folder2')  # go to some folder

with open(localfile, 'rb') as file_handler:
    ftp.storbinary(f'STOR {remotefile}', file_handler)
  1. use remote folder in remotefile
localfile  = 'test/input.txt'

remotefile = 'folder1/folder2/output.txt'

with open(localfile, 'rb') as file_handler:
    ftp.storbinary(f'STOR {remotefile}', file_handler)

In both situations folder has to exists. If it doesn't exist then you have to create it.

And first you has to create folder1 and later folder2, etc.

ftp.mkd('folder1')
ftp.mkd('folder1/folder2')

EDIT:

Full code which I used for tests

import ftplib

ftp = ftplib.FTP()
ftp.connect('0.0.0.0', 2121)  # pyftpdlib as default runs on port 2121
ftp.login()

# --- test 0 (create nested folders) ---

ftp.mkd('folder1')
ftp.mkd('folder1/folder2')

# --- test 1 ---

localfile  = 'test/input.txt'
remotefile = 'folder1/folder2/output1.txt'

with open(localfile, 'rb') as file_handler:
    ftp.storbinary(f'STOR {remotefile}', file_handler)

# --- test 2 ---

localfile  = 'test/input.txt'
remotefile = 'output2.txt'

ftp.cwd('folder1/folder2')

with open(localfile, 'rb') as file_handler:
    ftp.storbinary(f'STOR {remotefile}', file_handler)

I tested it on local FTP server using python module pyftpdlib

# install module

python -m pip install pyftpdlib

# run FTP server (with "write mode" for anonymous users)

python -m pyftpdlib --write

This server runs on port 2121 instead of standard 21

  • Related