Python If语句,在赋值之前引用错误局部变量“newfile”

2024-06-16 10:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的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)

Tags: 文件import脚本datetimeifoszipfilename
3条回答

尝试改变这个:

            if filedate:
                newfile = filename

在这方面:

^{pr2}$

你的问题是这段代码:

for filename in possibleFiles:
        filedate = re.search(string, filename)  
        if filedate:
            newfile = filename

newfile只定义if filedate。或者:

  • 检查您的输入,以便if filedate返回True。在
  • 将所有后续代码放在if子句下(通过额外的缩进),以便它只执行if filedate == True。在

问题就在这一行:

timestamp  = oftp.stat(newfile).st_atime

如果newfile之前没有基于If条件赋值,那么即使没有赋值,也会引用它。在

按照@cco的建议,在脚本的开头,您还可以将newfile设置为空字符串: newfile = ''

您应该构造为只有在分配了newfile时才处理其余部分。您可以在newfile上添加条件。在


另外,如果我没搞错的话,以下几行应该是for循环的一部分。否则,newfile将只包含最后找到的文件名。每次找到下一个时都会覆盖它。在

^{pr2}$

相关问题 更多 >