python分配变量困惑

标签 python syntax

我正在尝试编写一个脚本,1.列出目录的内容,创建它的列表(temp.txt),将列表转换为字符串并将其写入文件2.打开其他文本file(t.txt) 并将打开的文件的内容与之前保存的文件 (temp.txt) 进行比较并返回差异。这个想法是脚本能够判断文件夹中是否有新文件。函数 diff 作为独立脚本工作得很好,但当嵌套为函数时,我收到此错误消息:

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)

最佳答案

在函数中使用global li。据我了解,Python解释器只有在本地找不到全局变量时才会在全局范围内查找全局变量。将它们设置在本地方法中的某个位置(即使是在可能的“读取”之后)就足够了,以便解释器将它们绑定(bind)到本地范围,从而忽略任何全局声明并导致您看到的错误。

例如:

a = 3

def b():
    print a
    a = 1

将会失败,即使在执行print语句时全局定义了a。在函数体的开头添加 global a 即可使其正常工作。

关于python分配变量困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10581213/

相关文章:

python - Logilab 与 Python 27 windows 的兼容性吗?

python - Python中两个列表的点积

windows - 无法获得工作的符号链接(symbolic link)(Windows 7)cmd

安卓开发: Using intent syntax

java - setheight() 不改变变量

Python discord bot 警告特定的人

ms-word - 在 python 中使用 win32com.client 如何查找和替换多个文本

python - 找到一个被新行打断的长单词

c# - VS2010是否不符合C#4.0规范中的“用户定义的转换评估”?

c++ - 了解警告 : binding r-value to l-value reference