'issue with counting lines of python file
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?
Solution 1:[1]
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())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrGeek |
