gpt4 book ai didi

python分配变量困惑

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:25 25 4
gpt4 key购买 nike

我正在尝试编写一个脚本,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com