Irish Enigma Irish Enigma - 3 months ago 11
Python Question

Variable error in Python

I'm in a Python course and can't figure out why my code won't work:

import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")

for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()


The code above returns:

Traceback (most recent call last):
File "C:/Users/Kyle/Desktop/renamepy.py", line 5, in <module>
for file_name in file_list:
NameError: name 'file_list' is not defined
>>>


Why
file_name
is not defined?

Answer

Let's walk-through your code:

def rename_files():
    file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")

In you rename_files() function, you have defined a function that returns nothing. You have set a local scoped file_list that will be released and cannot be accessed once you're outside the function.

for file_name in file_list:
    os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()

Then when you're outside of the rename_files() function, you try to access a file_list that has not previously been initialized in the for-loop, so it throws the NameError

NameError: name 'file_list' is not defined

And then you called the rename_files() function but still file_list will not exist outside of the function.

There's several ways to ensure that file_list is materialized before you go through the for-loop.

Solution 1: Use the global variable.

file_list = []

def rename_files():
    global file_list
    file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
rename_files()
for file_name in file_list:
    os.rename(file_name, file_name.translate(None,"0123456789"))

Solution 2: take the file_list initialization outside of the function.

file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
    os.rename(file_name, file_name.translate(None,"0123456789"))

Solution 3 (as suggested by Karin): Put the for-loop into the function:

def rename_files():
    file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
    for file_name in file_list:
        os.rename(file_name, file_name.translate(None,"0123456789"))

Note: this is similar to Solution 2 since they are trying to put both the file_list initialization and the for-loop under the same scope.

Comments