UnboundLocalError:赋值前引用的局部变量'filehash'

时间:2015-08-10 05:30:51

标签: python

#!/usr/bin/python
import os
import hashlib
import sys

def dup_fileremove(dir):

    duplicate = []
    for filename in os.listdir(dir):
        if os.path.isfile(filename):
            filehash = md5.md5(file(filename).read()).hexdigest()
        if filehash not in duplicate:
            duplicate.append(filehash)
        else:
            os.remove(filename)
            print("removed : ", filename)

dup_fileremove("/tmp")

让我知道我错在哪里

4 个答案:

答案 0 :(得分:2)

如果filename不是文件,则不会创建filehash变量

答案 1 :(得分:1)

如果您的起始文件名不是文件,那么您将没有filehash变量,但即使在这种情况下,您也会检查filehash是否在重复列表中,这会导致您的问题。

另一个问题是你不会在每次迭代过程中重置filehash,如果你在列表中找到目录,这会导致问题,这会导致你删除它们,因为filehash将是以前的filehash。

另一个建议是使用set()而不是重复列表,因为在set中搜索更快。

示例 -

#!/usr/bin/python
import os
import hashlib
import sys

def dup_fileremove(dir):

    duplicate = set()
    for filename in os.listdir(dir):
        filehash = None
        if os.path.isfile(filename):
            filehash = md5.md5(file(filename).read()).hexdigest()
        if filehash not in duplicate:
            duplicate.add(filehash)
        else:
            os.remove(filename)
            print("removed : ", filename)

dup_fileremove("/tmp")

答案 2 :(得分:0)

您在分配之前致电filehash

duplicate.append(filehash)

可能无法创建filehash,因为in已在if案例中分配:

if os.path.isfile(filename):
    filehash = md5.md5(file(filename).read()).hexdigest()

你能做的是

def dup_fileremove(dir):
    filehash =None #Create filehash variable
    duplicate = []
    for filename in os.listdir(dir):
        if os.path.isfile(filename):
           filehash = md5.md5(file(filename).read()).hexdigest()
        if filehash and filehash not in duplicate: #Check if file hash is not None
           duplicate.append(filehash)
        else:
           os.remove(filename)
           print("removed : ", filename)

dup_fileremove("/tmp")

答案 3 :(得分:0)

工作脚本:

  

块引用

<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="mainCtrl">
    <div class="form-group">
        <label for="name" class="control-label">Name</label>
        <input id="nameid" ng-keyup="test()" ng-model="firstname" type="text" class="form-control" placeholder="Enter Name" required>
    </div>
    <p>{{editedname}}</p>
</div>
相关问题