如何用Python复制两个文件中指定标识间的测试用例日志内容
Extract Content Between Markers Across Multiple Log Files in Python
Got it, let's break this down. You need to pull the log content for a specific test case that's split between two different log files, bounded by the Start and End markers. Your existing code works for a single file, so we just need to adapt it to handle multiple files and maintain the "copy mode" state across them.
First, let's fix the small issues in your original code:
- Variable name inconsistencies (
inFilevsinfile,outFilevsoutfile) which would throw errors - It only processes one file, not the two you need
Here's a revised, robust solution that handles multiple log files and correctly captures the content between your markers:
# List of log files containing your test case logs target_logs = ["first_log.txt", "log2file.txt"] output_path = "parsed_test_case.log" # Track whether we're in the section we want to copy copy_active = False # Use 'with' statements to auto-manage file handles (prevents resource leaks) with open(output_path, "w") as output_file: for log_path in target_logs: with open(log_path, "r") as log_file: for line in log_file: cleaned_line = line.strip() # Trigger copy mode when we hit the start marker if cleaned_line == "Start": copy_active = True # Uncomment below if you want to include the Start marker in output # output_file.write(line) # Turn off copy mode when we hit the end marker elif cleaned_line == "End": copy_active = False # Uncomment below if you want to include the End marker in output # output_file.write(line) # Write lines to output if we're in copy mode elif copy_active: output_file.write(line)
Key Improvements & Notes:
- Multi-file support: We loop through a list of your log files, so you can easily add more later if needed.
- Safe file handling: Using
withensures files are automatically closed after processing, even if an error occurs. - Cross-file state retention: The
copy_activeflag stays consistent across files. So if your first log cuts off mid-test-case (afterStartbut beforeEnd), the second log's content will continue to be copied untilEndis found. - Flexibility: I added optional lines to include the
Start/Endmarkers in your output—just uncomment them if you need that.
Edge Cases to Consider:
- If your logs have multiple
Start/Endpairs (for different test cases), you'll want to modify the markers to include a test case ID (e.g.,Start: TestCase_007). Then update the condition to check for that specific string:if cleaned_line == "Start: TestCase_007": - Double-check that your markers don't have hidden whitespace or capitalization differences—
strip()helps with leading/trailing spaces, but if the marker has intentional spaces, adjust the comparison accordingly. - If you want to append to an existing output file instead of overwriting it, change the open mode from
"w"to"a".
内容的提问来源于stack exchange,提问作者Venkatesh Mendigeri
相关产品推荐
相关产品推荐

