Reputation: 117
def getcrc(lookfor,path):
abspath = basepath+path
for root, dirs, files in os.walk(abspath):
if lookfor in files:
#print "Found: %s" % join(root, lookfor)
filename = join(root,lookfor)
m = hashlib.md5()
for line in open(filename,'rb'):
m.update(line)
print "File",filename,"CRC is ",m.hexdigest()
return m.hexdigest()
I have made the above script to get the crc of a file, It works fine when the file name matches completely but I am not able to open that file when the Case sensitivity is violated, the file name is correct but i want to make this code case insensitive.
Below is the error I received :
Traceback (most recent call last):
File "C:\Users\darshanb\temp\de.ecw.python.QCsnapshot\src\XmlReaderTesting.py", line 80, in <module>
s3 = getcrc(filename,path)
File "C:\Users\darshanb\temp\de.ecw.python.QCsnapshot\src\Testing.py", line 51, in getcrc
for line in open(filename,'rb'):
UnboundLocalError: local variable 'filename' referenced before assignment
For E.g. I have a filename in the XML as 'Appointments_ecw_resource.xsl' for which i want to find the CRC but in the actual server the name is lower 'appointments_ecw_resource.xsl' sometimes it is upper case do, Is there a way that I can ignore the case sensitivity check.
Upvotes: 0
Views: 156
Reputation: 1122312
You can match a file case insensitively by using any()
and a generator expression:
lookfor = lookfor.lower()
if any(lookfor == fname.lower() for fname in files):
However, you still need to indent the for
loop to fall within the if
statement, because if your looked-for filename is not there, you still need to not read the file:
lookfor = lookfor.lower()
if any(lookfor == fname.lower() for fname in files):
#print "Found: %s" % join(root, lookfor)
filename = join(root,lookfor)
m = hashlib.md5()
for line in open(filename,'rb'):
m.update(line)
print "File",filename,"CRC is ",m.hexdigest()
return m.hexdigest()
Upvotes: 1
Reputation: 5721
Looks like your filename
variable is defined in an inner scope of preceding if
statement. Initialize it outside of this scope or move your for
loop inside (depending on the purpose).
Upvotes: 2