我有兩個功能。第一個用于獲取文本檔案的路徑串列,第二個用于迭代此路徑串列,然后檢查它們是否包含單詞密碼。但是由于第二個函式中的 Try except 陳述句,我不得不使用遞回來使其繼續運行,除非如果可能在下面提供另一種方法。我的問題是第二個函式中回傳的串列是空的,為什么以及如何修復它?
def search_txt():
"""Function to search the C:\\ for .txt files -> then add them (including full path to file) to a list."""
list_of_txt = []
for dir_path, sub_dir, files in os.walk("C:\\"):
"""Method 1 -> checks the end of the file name (could be used for specific extensions)"""
for file in files:
if file.endswith(".txt"):
list_of_txt.append(os.path.join(dir_path, file))
return list_of_txt
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
if len(list_of_files) != 0:
for i in range(len(list_of_files)):
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
except UnicodeDecodeError:
return search_pass_file(list_of_files)
except PermissionError:
return search_pass_file(list_of_files)
else:
return list_of_pass
if __name__ == '__main__':
myList = search_txt()
print(search_pass_file(myList))
uj5u.com熱心網友回復:
list_of_pass只有當len(list_of_files) == 0(它在 else 塊中)時,您才會回傳。您的 return 陳述句應該在回圈之后發生(應該是while一個順便說一句)
您可以通過將它們放在括號中來排除一行中的多個錯誤:except (UnicodeDecodeError, PermissionError)of except all exceptions(例如,您沒有處理FileNotFoundError)。
我會將您的功能簡化為:
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
while list_of_files:
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
break
except Exception:
list_of_pass = search_pass_file(list_of_files)
return list_of_pass
編輯:同樣在您的 except 塊中,您應該將遞回函式的回傳值附加到,list_of_pass否則您將丟失錯誤發生后找到的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/497501.html
標籤:python-3.x 列表 文件 递归 蟒蛇操作系统
上一篇:最長回文子串長度
