I’m trying to write a script that 1. lists the content of a directory, creates a list of it(temp.txt), turns the list into a string and writes it into a file 2. opens an other text file(t.txt) and compares the content of the opened file with the previously saved file (temp.txt) and returns the difference. The idea is that the script would be able to tell if there are new files in a folder. The function dif works great as a standalone script but when nested as a function I get this error message:
Enter directory > /users
Traceback (most recent call last):
File "/Users/alkopop79/NetBeansProjects/comparefiles.py", line 33, in <module>
dir()
File "/Users/alkopop79/NetBeansProjects/comparefiles.py", line 12, in dir
li.append(fname)
UnboundLocalError: local variable 'li' referenced before assignment
and the script:
import os
li = []
lu = []
le = []
def dir():
dir = raw_input("Enter directory > ")
path=dir # insert the path to the directory of interest
dirList=os.listdir(path)
for fname in dirList:
li.append(fname)
li = ','.join(str(n) for n in li)
targetfile = open("temp.txt", 'w')
targetfile.write(li)
targetfile.close()
print li
def open_file():
txt = open('t.txt')
li = txt.read()
la = li.split()
return la
print len(li)
def open_another():
txt = open('temp.txt')
lu = txt.read()
lo = lu.split()
return lo
print len(li)
dir()
a = open_file()
b = open_another()
print set(a) & set(b)
Use
global liinside your functions. From what I understand, the Python interpreter will look for globals at the global scope only if it cannot find them locally. It is enough that they are set somewhere in the local method (even if it’s after a possible “read”) for the interpreter to bind them to local scope, thus ignoring any global declaration and resulting in the error that you see.For instance:
Will fail, even though
ais defined globally at the time theprintstatement is executed. Addingglobal aat the beginning of the function body would make it work.