Python 3.x脚本开发:提取input.txt前5个单奇数行及整数判断指引
Solution to Your File Line Filtering Problem
1. How to Check if a Line Contains Exactly a Single Integer
Let’s start with the core validation logic—this is what will let you tell if a line meets your basic requirement:
- Clean the line first: Use
strip()to wipe out leading/trailing whitespace (newlines, spaces, tabs all count here). This avoids false negatives from lines like17that have extra spaces around the number. - Confirm it’s a single element: Split the cleaned line with
split()(it splits on any whitespace by default). If the resulting list has a length of 1, you know there’s only one item in the line. - Validate it’s an integer: Use a
try-exceptblock to convert the element to an integer. This works for both positive and negative numbers (unlikestr.isdigit(), which fails for negatives like-21). If conversion throws aValueError, the line doesn’t have a valid integer.
2. Complete Python 3.x Script
Here’s the full, polished script that does exactly what you need—reads input.txt, filters for lines with only a single odd integer, and outputs the first 5 matches:
def extract_first_five_odds(): valid_line_count = 0 # Open the file safely (auto-closes when done) with open("input.txt", "r") as input_file: for line in input_file: # Stop early once we have 5 valid lines if valid_line_count >= 5: break cleaned_line = line.strip() # Skip empty lines entirely if not cleaned_line: continue # Check if there's only one element in the line line_elements = cleaned_line.split() if len(line_elements) != 1: continue # Try converting to integer to rule out non-numeric content try: number = int(line_elements[0]) except ValueError: continue # Verify it's an odd number (works for negatives too!) if number % 2 != 0: print(number) valid_line_count += 1 if __name__ == "__main__": extract_first_five_odds()
Key Logic Breakdown:
with open(...): Handles file opening/closing safely, so you don’t have to worry about resource leaks.- Early exit: Stops processing lines as soon as we’ve found 5 valid ones—great for large files where you don’t need to read every line.
- Multi-layer validation: Rejects lines with multiple numbers, non-numeric text, even numbers, or blank content—covers all your edge cases.
- Negative odd support: The modulo check works for negative integers like
-3or-19, so those won’t get missed.
内容的提问来源于stack exchange,提问作者y_yogi
相关产品推荐
相关产品推荐

