我想写一个脚本,1.列出目录的内容,创建一个列表(temp.txt),将列表变成一个字符串,并将其写入文件2。打开另一个文本文件(t.txt),并将打开的文件的内容与先前保存的文件(temp.txt)进行比较并返回差异。这个想法是,脚本能够判断文件夹中是否有新文件。该功能DIF作为一个独立的脚本的伟大工程,但作为嵌套函数时,我收到此错误信息:蟒蛇分配变量混乱
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
和脚本:
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')。请记住,Python函数可以接受参数并可以返回一个或多个值。 – NPE
'dir'是一个内置函数的名称,不应该像这样隐藏。 –