I have got a setup where a file is being placed in my FTP server directory regularly. I am looking for the best way to pull it into my Python script. The catch is that the name changes every time the file is deposited. I.e. the first file is FILE0001.CSV
, the second is FILE0002.CSV
, the third FILE0003.CSV
, and so on. My current idea is to store a variable with value 1
in a txt, extract that variable, add one to it, use it to reference the file, and then re-store the variable. Something like this (assuming the txt with the value has already been created and is in the folder):
with open('count.txt') as fp:
c = int(fp.read())
c = c+1
ftp = FTP('localhost')
ftp.login(username, password)
ftp.cwd('dropoff')
with open('FILE000' + c + '.CSV', 'wb') as fp:
ftp.retrbinary('RETR FILE000' + c + '.CSV', fp.write)
ftp.quit()
with open('count.txt', 'w') as fp:
fp.write(str(c))
This seems like a bit of a roundabout way to do it, is there is a better and/or more direct way?
There is no way to change the incoming file name or keep the name and overwrite it.
If there's only the only file on the server, ask the server for its name and download it:
ftp.cwd('dropoff')
files = ftp.nlst()
if (len(files) != 1):
raise Exception("Expected only one file")
thefile = files[0]
with open(thefile, 'wb') as fp:
ftp.retrbinary('RETR ' + thefile, fp.write)