gpt4 book ai didi

用于查找包含文本字符串的文件的 Python 脚本

转载 作者:行者123 更新时间:2023-12-01 07:42:04 25 4
gpt4 key购买 nike

用于查找包含文本字符串的文件的 Python 脚本

我想找到一个包含特定字符串的文本文件。

下面是没有找到匹配的文件名和匹配的行号。

import os

search_path = "C:\\Users\\xx\\Desktop\\text_file\\" #folder to search
file_type = ".txt" #filetype to search
search_str = " INTERIM BILL-SUMMARY" #string to search

if not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present
search_path = search_path + "/"
if not os.path.exists(search_path): # If path does not exist, set search path to current directory
search_path ="."
for fname in os.listdir(path=search_path): # Repeat for each file in the directory
if fname.endswith(file_type): # Apply file type filter
fo = open(search_path + fname) # Open file for reading
line = fo.readline() # Read the first line from the file
line_no = 1 # Initialize counter for line number
while line != '' : # Loop until EOF
index = line.find(search_str) # Search for string in line
if ( index != -1) :
print(fname, "[", line_no, ",", index, "] ", line, sep="")
line = fo.readline() # Read next line
line_no += 1 # Increment line counter
fo.close() # Close the files

最佳答案

您能尝试一下吗,并告诉我它是否适合您?

import os

search_path = "C:\\Users\\xx\\Desktop\\text_file\\" #folder to search
file_type = ".txt" #filetype to search
search_str = "INTERIM BILL-SUMMARY" #string to search

if not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present
search_path = search_path + "/"
if not os.path.exists(search_path): # If path does not exist, set search path to current directory
search_path ="."
for fname in os.listdir(path=search_path): # Repeat for each file in the directory
if fname.endswith(file_type): # Apply file type filter
with open(search_path + fname) as f: # Open file for reading
for line_no, line in enumerate(f):
if search_str in line:
print(fname, "[", line_no, ",", line.find(search_str), "] ", line, sep="")

关于用于查找包含文本字符串的文件的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56647363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com