python - 为什么这个变量不是全局的(不能在函数中使用)?
问题描述
我知道我必须使用global关键字来访问变量,但我的问题是为什么它不能在函数中使用?
source = "C:/ALL IN ONE/Test File"
temp = "C:/ALL IN ONE/Temp Folder"
num_files = 0
def sort():
if not os.path.exists(temp):
os.makedirs(temp)
for folder_path, folder, files in os.walk(source):
for file in files:
num_files += 1 # I can't seem to access the variable "num_files" outside the function
if file.endswith("txt"):
pass
解决方案
您global
在函数中定义变量,如下所示:
num_files = 0
def sort():
global num_files
# rest of your code
在没有将其声明为全局的情况下,要执行num_files += 1
基本上是num_files = num_files + 1
,该函数会搜索已初始化局部变量的声明num_files
以访问其赋值右侧的值,但没有任何值,因此会引发UnboundLocalError: local variable referenced before assignment
异常。
请参阅文档。
推荐阅读
- typescript - 如何创建异步和等待循环,直到使用打字稿获得结果?
- javascript - Javascript - 检查是否最后是空的
- git - git“浅层克隆+非浅层”与“普通克隆”
- reactjs - Github 上 React 组件目录的问题
- pyspark - 在 Databricks 中清理 Delta 表不起作用
- ajax - firefox/cors 不允许在 POST 请求中使用 application/json contentType?
- c++ - 如何处理 QTcpServer 中的 TLS 握手超时?
- python - 尝试加载 PyTorch 模型时出现大小不匹配运行时错误
- python - 在文本框 Tkinter 中打印 numpy 输出
- c# - 根 Pickles_FeatureDirectory 上的 Pickles 解析错误