我正在遍歷一個目錄,如果找到 python 檔案,則嘗試查找其中的代碼行數。我不太確定為什么我會遇到以下問題。
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}" //
)
錯誤:
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:
如果我洗掉該行,代碼將按預期作業。里面有一個單行代碼。這里有什么指導嗎?
uj5u.com熱心網友回復:
filedirpath是檔案的名稱,而不是其路徑,要獲取其完整路徑,請使用.將名稱與目錄路徑連接起來os.path.join。with此外,在處理檔案時最好使用陳述句,因為它會自動關閉檔案:
file_path = os.path.join(dirpath, file)
with open(file_path) as f:
num_lines = len(f.readlines())
uj5u.com熱心網友回復:
你也可以試試這個方法。您必須獲取os.path.abspath(file)檔案的路徑,然后才能打開它。
并始終contect_managers用于 IO 操作。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427713.html
上一篇:拆分檔案的內容
