【发布时间】:2020-04-14 18:10:48
【问题描述】:
需要帮助,我是 python 新手, 我写了一个脚本,它应该在一个目录中找到所有文件,只处理那些有特定行的文件,跳过那些没有该行的文件。具体的行是‘, Run Time’ 它无法仅处理我需要的文件,它会处理所有文件。
要查找的所有行:
- ',"运行时间'
- ‘,”开始时间’
- ‘,”结束时间’
- ‘Test_ID e:’
- ‘测试程序名称:’
- “产品:”
第 1、2 和 3 行是重复行,我都需要它们, 第 4、5 和 6 行也在重复,但我只需要捕获它们。
导入操作系统
runtime_l = '," Run Time'
start_tm = '," Start Time'
end_tm = '," End Time'
test_ID = ' Host Name: '
program_n = 'Test Program Name:'
prod_n = 'Product:'
given_path = 'C:\\02\\en15\\TST'
for filename in os.listdir(given_path):
filepath = os.path.join(given_path, filename)
if os.path.isfile(filepath):
print("File Name: ", filename)
print("File Name\\Path:", filepath)
with open(filepath) as mfile:
for line in mfile:
if runtime_l in line:
# do something with the line
print(line)
if start_tm in line:
# do something with the line
print(line)
if end_tm in line:
# do something with the line
print(line)
if test_ID in line:
# do something with the line
print (line)
if program_n in line:
# do something with the line
print (line)
if prod_n in line:
# do something with the line
print (line)
else:
继续
如果一个文件有“运行时间”行,我将如何测试它。 不确定它是否是“pythony”外观的脚本,但它可以满足我的需要。它会找到包含我想要的行的文件并处理它们。
import os
runtime_l = '," Run Time'
start_tm = '," Start Time'
end_tm = '," End Time'
given_path = 'C:\\02\\en15\\TST'
for filename in os.listdir(given_path):
filepath = os.path.join(given_path, filename)
if os.path.isfile(filepath):
#print("File Name: ", filename)
#print("File Name\\Path:", filepath)
with open(filepath) as mfile:
for line in mfile:
if runtime_l in line:
#runtime_file = open(filepath, 'r')
with open(filepath) as runtime_file:
for rn_l in runtime_file:
if runtime_l in rn_l:
print (rn_l)
elif start_tm in rn_l:
print (rn_l)
elif end_tm in rn_l:
print (rn_l)
【问题讨论】:
-
托德,谢谢你的回答,但这不是我想要的,或者我不明白你的回答。首先,我只需要处理具有“运行时间”行的文件。其次,我只需要捕获第 4,5 和 6 行的第一个匹配项,请参阅原始请求。感谢您的帮助!
-
托德!非常感谢您的帮助,但我是 Python 新手,您的提示可能很棒,但我无法使用它们 - 我不理解它们。
-
如何测试目录中的文件以查找文件是否有行(运行时),如果有,我需要处理它并忽略那些没有行的文件。我需要使用(运行时)字符串处理所有文件。需要找到 6 个特定的行(见原帖)。对于 ines 4、5、6,我只想打印(该行的)第一个匹配项。如果脚本找到匹配第 4、5、6 行的 10 或 15 行,我只需要打印每行的 1 个匹配项。
-
您将不得不打开每个文件并读取一些文本以确定是否应该处理文件的其余部分。没有办法解决这个问题。唯一的问题是您希望在文件中的哪个位置找到该文本 - 您可能只读取文件的前 n 行或最后 n 行(使用
seek())来检查它,然后处理整个文件如果找到。
标签: python-3.x search