0

I am traversing a directory, and if python file is found, trying to find the number of lines of code in it. I am not really sure why I face the below issue.

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):

    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            num_lines = len(open(file).readlines()) #causes issue
            print(
                f"Root:{dirpath}\n"
                f"file:{file}\n\n"
                f"lines: {num_lines}" //
            )

Érror:

Traceback (most recent call last):
  File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
    num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory: 

If i remove that line, the code works as expected. There is a single line code within. Any guidance here?

2 Answers 2

3

file is the file's name, not its path, to get its full path, join the name with the directory path dirpath using os.path.join. Also, it is better to use a with statement when dealing with files since it automatically closes the file:

file_path = os.path.join(dirpath, file)

with open(file_path) as f:
    num_lines = len(f.readlines())
Sign up to request clarification or add additional context in comments.

Comments

0

You can also try this way. You have to get the os.path.abspath(file) path of the file then only it'll open.

and always with contect_managers for IO operation.

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            try:
                with open(os.path.abspath(file)) as f:
                    print(len(f.readlines()))
                    print(os.path.abspath(file))
            except:
                pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.