Python Forum
'' FTP '' File upload with a specified string and rename - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: '' FTP '' File upload with a specified string and rename (/thread-39811.html)



'' FTP '' File upload with a specified string and rename - midomarc - Apr-17-2023

Transfer a file in Local folder to a folder in FTP server and rename

I need to upload a file start with a specified string (0001) to an FTP server

My code it's working Only if give it the full filename = 0001_2655545XXXX

I need to upload a file if it is start with a string (0001) Without specifying the full name

import os, sys, stat
import ftplib
from ftplib import FTP

def ftpPush(src, filename , dst, new_name):
    ftp = FTP('xxxxxx', user='xxx', passwd='xxxx')
    ftp.cwd(dst)
    ftp.storlines("STOR "+filename, open(src+filename, 'rb'))
    ftp.rename(filename, new_name)
    ftp.quit()

src = '/' #path local
dst = '//'  #path server FTP

new_name = "Test1"
filename = []

for fileName in os.listdir(src):
    if filename.startswith('0001'):
       ftpPush(src, filename, dst, new_name)

print("File uploaded and renamed successfully!")



RE: (Please help me) '' FTP '' File upload with a specified string and rename - bowlofred - Apr-17-2023

Line 17 creates a list called filename
Line 19 assigns the current filename in the listdir to fileName
Line 20 tries to evaluate filename.startswith(), but there is no such method for a list. So this should exist with an exception.

I don't see how this would work if you gave the full filename at all. Is this the exact code that you ran?


Also line 8 uses src+filename, But that's liable to create a string that has no path separator between the directory and the filename. Preferable to use Path syntax here. I'd expect the open() to fail in that case.

Do you get any errors?