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)
li,lu,le). Remember that a Python function can accept arguments and can return one or more values.diris the name of a built-in function, which ought not be hidden like this.