【问题标题】:Python - If statement, error local variable 'newfile' referenced before assignmentPython - If 语句,分配前引用的错误局部变量“newfile”
【发布时间】:2018-07-25 23:53:54
【问题描述】:

我有以下 Python 2.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)

【问题讨论】:

    标签: python python-2.7 pysftp


    【解决方案1】:

    你的问题在于这段代码:

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

    newfile 只被定义为if filedate。要么:

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

    【讨论】:

    • 感谢您的帮助。您能否分享一些示例代码,说明我将如何实施您的建议?干杯
    • @NickEdwards。不幸的是,我不能,因为你没有提供一个可重复的例子,或者澄清你想要你的输出是什么。
    • 脚本一直工作,直到它到达 CSV 中不在 FTP 上的文件名。输出是脚本只是移动到 csv 中的下一行并按原样继续。我不能包含要复制的 ftp 凭据,因为那里有敏感数据。干杯
    【解决方案2】:

    尝试改变这个:

                if filedate:
                    newfile = filename
    

    进入这个:

                if filedate and filename is not none:
                    newfile = filename
    

    【讨论】:

      【解决方案3】:

      问题出在这一行:

      timestamp  = oftp.stat(newfile).st_atime
      

      如果之前没有根据 if 条件分配 newfile,即使没有分配,您也会引用它。

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

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


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

      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"
      

      【讨论】:

      • 如果未设置filedate,这仍然会引发错误。您需要在循环之前将newfile 设置为一个虚假值(大概是0None)。
      • @KevinLemaire - 感谢您的帮助。欣赏它。您能否举个例子说明我应该如何实施您的建议?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2014-08-20
      • 1970-01-01
      • 2020-09-22
      • 2013-02-28
      • 2022-11-14
      相关资源
      最近更新 更多