Python中ftp的os.renames

0 投票
1 回答
1397 浏览
提问于 2025-04-17 14:24

我想用Python把很多文件从Windows系统转移到一个Unix的FTP服务器上。我有一个CSV文件,里面记录了当前文件的完整路径和文件名,以及要发送到的新基础路径(可以在这里查看示例数据集)。

我写了一个脚本,使用os.renames来在Windows上进行文件转移和目录创建,但我还没找到一个简单的方法通过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

我尝试过在这个链接上的方法,但那个是用来移动一个目录下的所有文件的。我现在有旧的和新的完整文件名,只需要它能创建中间的目录。

谢谢,

1 个回答

1

下面的代码可能有效(还没有测试过):

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'))

撰写回答