我有下面的python2.7脚本。在
该脚本遍历包含文件名的CSV文件,然后在FTP服务器上查找文件名。在
但是,在ftp上找不到文件时,我得到一个错误:
赋值前引用局部变量“newfile”时出错
理想情况下,如果在ftp上找不到上一个文件,我希望脚本只移动到文件的下一行。我该怎么做?提前谢谢。在
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)
尝试改变这个:
在这方面:
^{pr2}$你的问题是这段代码:
newfile
只定义if filedate
。或者:if filedate
返回True
。在if
子句下(通过额外的缩进),以便它只执行if filedate == True
。在问题就在这一行:
如果
newfile
之前没有基于If条件赋值,那么即使没有赋值,也会引用它。在按照@cco的建议,在脚本的开头,您还可以将
newfile
设置为空字符串:newfile = ''
您应该构造为只有在分配了
newfile
时才处理其余部分。您可以在newfile
上添加条件。在另外,如果我没搞错的话,以下几行应该是for循环的一部分。否则,
^{pr2}$newfile
将只包含最后找到的文件名。每次找到下一个时都会覆盖它。在相关问题 更多 >
编程相关推荐