我需要将一些文件上传到ftp服务器上的不同目录中。这些文件的名称如下:
必须将它们放入下一个目录:
我想要这样的东西:对于像External这样的文件名把它放到外部目录中。 我有下一个代码,但是这会将所有zip文件放入“Broad”目录中。我只想将broad.zip文件放入这个目录,而不是全部。
def upload_file():
route = '/root/hb/zip'
files=os.listdir(route)
targetList1 = [fileName for fileName in files if fnmatch.fnmatch(fileName,'*.zip')]
print 'zip files on target list:' , targetList1
try:
s = ftplib.FTP(ftp_server, ftp_user, ftp_pass)
s.cwd('One/Two/Broad')
try:
print "Uploading zip files"
for record in targetList1:
file_name= ruta +'/'+ record
print 'uploading file: ' + record
f = open(file_name, 'rb')
s.storbinary('STOR ' + record, f)
f.close()
s.quit()
except:
print "file not here " + record
except:
print "unable to connect ftp server"
答案 0 :(得分:0)
该函数具有s.cwd
的硬编码值,因此它将所有文件放在一个目录中。您可以尝试类似下面的内容,从文件名中动态获取远程目录。
示例:(未经过测试)
def upload_file():
route = '/root/hb/zip'
files=os.listdir(route)
targetList1 = [fileName for fileName in files if fnmatch.fnmatch(fileName,'*.zip')]
print 'zip files on target list:' , targetList1
try:
s = ftplib.FTP(ftp_server, ftp_user, ftp_pass)
#s.cwd('One/Two/Broad') ##Commented Hard-Coded
try:
print "Uploading zip files"
for record in targetList1:
file_name= ruta +'/'+ record
rdir = record.split('_')[0] ##get the remote dir from filename
s.cwd('One/Two/' + rdir) ##point cwd to the rdir in last step
print 'uploading file: ' + record
f = open(file_name, 'rb')
s.storbinary('STOR ' + record, f)
f.close()
s.quit()
except:
print "file not here " + record
except:
print "unable to connect ftp server"