0

I am trying to loop through 20 newsgroup dataset, at the end i join all the files under a variable called file_path. However, i am getting the following error at the next line :

name 'file_path' is not defined

import os
for (root,dirs,files) in os.walk(my_directory):
    for special_file in files:
        if special_file.endswith(''):
            file_path = os.path.join(root, special_file)

What is my mistake? clearly i have defined file_path correctly.

4
  • 4
    most likely because the loop is never reaching file_path = os.path.join(root, special_file (is if special_file.endswith(''): your actual condition? That is always true for all strings). Commented May 13, 2020 at 5:31
  • I removed the not necessary loop but still the file_path is not recognized, for (root,dirs,files) in os.walk(my_directory): file_path = os.path.join(root, files) Commented May 13, 2020 at 5:41
  • 1
    what my_directory is assigned to and can you print full error message from console? Commented May 13, 2020 at 5:46
  • Sorry, my bad. Its the directory path, which was not correctly written. The code now runs. Commented May 13, 2020 at 5:59

1 Answer 1

1

Using variables which are exclusively declared in a conditional statement is bad design. Define either a default file_path as fallback or don't use it outside of the conditional statement where it's defined.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.