![](/img/trans.png)
[英]How to search for file in folder containing specific text and rename that file in Python
[英]How to search and read a text file in a specific folder faster using python
我編寫了一個簡單的 python 腳本來搜索文件夾中的日志文件(大約有 400 萬個文件)並讀取該文件。 目前,整個操作的平均時間為 20 秒。 我想知道是否有一種方法可以更快地獲得響應。
下面是我的腳本
import re
import os
import timeit
from datetime import date
log_path = "D:\\Logs Folder\\"
rx_file_name = r"[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}"
log_search_script = True
today = str(date.today())
while log_search_script:
try:
log_search = input("Enter image file name: ")
file_name = re.search(rx_file_name, log_search).group()
log_file_name = str(file_name) + ".log"
print(f"\nLooking for log file '{log_file_name}'...\n")
pass
except:
print("\n ***** Invalid input. Try again! ***** \n")
continue
start = timeit.default_timer()
if log_file_name in os.listdir(log_path):
log_file = open(log_path + "\\" + log_file_name, 'r', encoding="utf8")
print('\n' + "--------------------------------------------------------" + '\n')
print(log_file.read())
log_file.close()
print('\n' + "--------------------------------------------------------" + '\n')
print("Time Taken: " + str(timeit.default_timer() - start) + " seconds")
print('\n' + "--------------------------------------------------------" + '\n')
else:
print("Log File Not Found")
search_again = input('\nDo you want to search for another log ("y" / "n") ?').lower()
if search_again[0] == 'y':
print("======================================================\n\n")
continue
else:
log_search_script = False
你的問題是這條線:
if log_file_name in os.listdir(log_path):
這有兩個問題:
os.listdir
將創建一個巨大的列表,這可能需要大量時間(和空間......)。... in...
部分現在將 go 在這個巨大的列表上線性搜索並搜索文件。相反,讓您的操作系統完成艱苦的工作並“ 請求寬恕,而不是許可” 。 假設文件在那里並嘗試打開它。 如果它實際上不存在 - 將引發錯誤,我們將捕獲:
try:
with open(log_path + "\\" + log_file_name, 'r', encoding="utf8") as file:
print(log_file.read())
except FileNotFoundError:
print("Log File Not Found")
您可以使用 glob。
import glob
print(glob.glob(directory_path))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.