代码显示python 2.7中的未定义错误

时间:2017-09-15 09:53:06

标签: python

我的代码是:

import os
def rename_files():
#1 list all files in one variable
 file_list = os.listdir(r"C:\Users\Kai Uchiha\Desktop\PYTHON\prank")
print(file_list)
#2 rename those files

rename_files()

并显示错误:

  

Traceback(最近一次调用最后一次):文件“C:/ Users / Kai   宇智波/桌面/项目/实验/ experiment2.py“,第5行,in          print(file_list)NameError:未定义名称'file_list'

2 个答案:

答案 0 :(得分:2)

您需要缩进print(file_list)行,以便它实际上是rename_files函数的一部分:

def rename_files():
  #1 list all files in one variable
  file_list = os.listdir(r"C:\Users\Kai Uchiha\Desktop\PYTHON\prank")
  print(file_list)  # NOTE: additional indent!

按原样,该行是函数的外部,并且那里不存在file_list变量,因此您看到的错误。

答案 1 :(得分:1)

您有缩进错误

import os
def rename_files():
#1 list all files in one variable
 file_list = os.listdir(r"C:\Users\Kai Uchiha\Desktop\PYTHON\prank")
 print(file_list) # Added tab here (it seems that it's only one space for you, but I think it still has to be four spaces...
#2 rename those files

rename_files()