简体   繁体   中英

How do I execute ftp “put C:\path\to\file” in Python

I am trying to upload a file to an FTP server, I wanted to write a Python script to simplify the process. Currently I ftp to the server and execute these commands:

quote allo file_size_in_bytes

put c:\path\to\file

This is what I have so far, I am not able to get the file to transfer using the put command.

from ftplib import FTP
import os
import time
from subprocess import call

ip = raw_input('Enter ip address: ')                           # User input for host
print ip                                                       # Prints host 
filelocation = raw_input('Drag file here: ')                   # File to upload  
print ('This is the local file '+filelocation)                 # Verify file location
filename = os.path.basename(filelocation)                      # If a File name is needed
filesize = os.path.getsize(filelocation)                       # Need file size in bytes for quote allo command
print ('This is the file size in bytes '+str(filesize))        # Verify correct size
time.sleep(2)                                                  # Pause to look at screen
ftp = FTP(ip)                                                  # Open ftp connection
ftp.login('user','pass')                                       # Login
print ftp.getwelcome()                                         # Verify proper connection
remotepath = ftp.pwd()+filename                                # If a remote path to ftp server is needed
print ('This is the file path on the processor '+remotepath)   # Verify remote path
"\"quote\""                                                    # Need this, not sure why
ftp.sendcmd('allo '+str(filesize))                             # quote allo filesize, seems to work
#"\"put\""                                                     # Experimenting, don't know if this is needed
call(['echo "put C:\filelocation" | ftp'])                     # This doesn't appear to work
time.sleep(5)
ftp.quit()

You are logging in with ftplib, yet you are trying to run an external ftp process for the upload itself. That cannot work as the external ftp process does not know about your ftplib FTP session.

To upload a file using the ftplib, use storbinary or storlines method.

See for example Python Script Uploading files via FTP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM