os.renames for ftp in python

2019-08-29 23:07发布

问题:

I want to move a large number of files from a windows system to a unix ftp server using python. I have a csv which has the current full path and filename and the new base bath to send it to (see here for an example dataset).

I have got a script using os.renames to do the transfer and directory creation in windows but can figure out a way to easily do it via ftp.

import os, glob, arcpy, csv, sys, shutil, datetime
top=os.getcwd()
RootOutput = top
startpath=top
FileList = csv.reader(open('FileList.csv'))
filecount=0
successcount=0
errorcount=0

# Copy/Move to FTP when required
ftp = ftplib.FTP('xxxxxx')
ftp.login('xxxx', 'xxxx')
directory = '/TransferredData'
ftp.cwd(directory)

##f = open(RootOutput+'\\Success_LOG.txt', 'a')
##f.write("Log of files Succesfully processed. RESULT of process run @:"+str(datetime.datetime.now())+"\n")
##f.close()
##
for File in FileList:
    infile=File[0]
    # local network ver
    #outfile=RootOutput+File[4]
    #os.renames(infile, outfile)

    # ftp netowrk ver
#    outfile=RootOutput+File[4]
#    ftp.mkd(directory)

    print infile, outfile

I tried the process in http://forums.arcgis.com/threads/17047-Upload-file-to-FTP-using-Python-ftplib but this is for moving all files in a directory, I have the old and new full file names and just need it to create the intermediate directories.

Thanks,

回答1:

The following might work (untested):

def mkpath(ftp, path):
    path = path.rsplit('/', 1)[0] # parent directory
    if not path:
        return
    try:
        ftp.cwd(path)
    except ftplib.error_perm:
        mkpath(ftp, path)
        ftp.mkd(path)

ftp = FTP(...)
directory = '/TransferredData/'

for File in FileList:
    infile = File[0]
    outfile = File[4].split('\\') # need forward slashes in FTP
    outfile = directory + '/'.join(outfile)
    mkpath(ftp, outfile)
    ftp.storbinary('STOR '+outfile, open(infile, 'rb'))