I have following Python 2.7 script.
The script iterates through a CSV file that contains filenames, it then looks on an FTP server to try and find the filenames.
However, I get an error when the file isn't found on the ftp:
error local variable 'newfile' referenced before assignment
Ideally, I want the script to just move on to the next row in the file, if it can't find the previous file on the ftp. How would I do this? Thanks in advance.
def googleclouda(googlefile):
import time
import pysftp
import sys
import os
from os import path
from datetime import datetime
import calendar
import zipfile
import re
os.chdir("C:\Users\\xxx\python\\xxx\\")
oftp = pysftp.Connection(host="xxxxxx", username="xxxxxx", password="xxxxxx")
d = datetime.utcnow()
unixtime=calendar.timegm(d.utctimetuple())
month = datetime.now().strftime("%m")
string = googlefile+month+".*\.txt$"
possibleFiles = oftp.listdir("/")
for filename in possibleFiles:
filedate = re.search(string, filename)
if filedate:
newfile = filename
timestamp = oftp.stat(newfile).st_atime
if timestamp > unixtime - 604800:
newtime=unixtime + 3600
gaamfile='file_123_26807_'
zipname = gaamfile+str(newtime)+'.sync.zip'
create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
oftp.get(newfile, newfile)
oftp.close()
newfilename = gaamfile+str(newtime)+'.sync'
os.rename(newfile, newfilename)
create_zip.write(newfilename)
create_zip.close()
print newfile
else:
print "No files found"
filecsv = 'filelist.csv'
with open(filecsv, 'r') as f:
for line in f:
if not line.startswith('\n'):
googlefile = line.strip()
googleclouda(googlefile)