如何实现忽略注释块并拼接反斜线续行的Python生成器函数?
Fixing Your File Line Generator with Comment Handling & Line Continuation
Let's break down what's tripping up your current code first:
- You're handling comments before resolving line continuations, which means comment lines that use backslashes to continue get misclassified as regular content later
- The class structure isn't being used correctly (you defined a static method but tried to call it like a standalone function)
- You're not using a
withblock for safe file handling (a Python best practice) - The final iteration logic is broken (looping over
Linesand callingnext(gen)each time will cause unexpected behavior)
Here's the corrected generator function that follows your desired priority: resolve line continuations first, then process comments:
import sys from typing import Iterator def get_filelines(path: str) -> Iterator[str]: current_line_buffer = [] with open(path, 'r') as file: for raw_line in file: # Strip only the trailing newline, preserve other whitespace cleaned_line = raw_line.rstrip('\n') # Skip full comment lines that haven't been started as part of a regular line if not current_line_buffer and cleaned_line.lstrip().startswith('#'): continue # Add the current line to our buffer current_line_buffer.append(cleaned_line) # Check if this line ends with a continuation backslash if cleaned_line.endswith('\\'): # Remove the backslash and keep building the line current_line_buffer[-1] = current_line_buffer[-1][:-1] continue # We have a complete line—now process comments full_combined_line = ''.join(current_line_buffer) current_line_buffer = [] # Reset buffer for next line # Handle inline comments: split at the first # and keep the preceding content if '#' in full_combined_line: processed_line = full_combined_line.split('#', 1)[0].rstrip() else: processed_line = full_combined_line.rstrip() # Only yield non-empty lines after processing if processed_line: yield processed_line # Example usage if __name__ == "__main__": try: for line in get_filelines('path/to/file.txt'): print(line) except FileNotFoundError: print("File could not be found. Please check spelling of file name!") sys.exit()
Key Logic Breakdown:
Line Continuation Handling:
- We use a buffer (
current_line_buffer) to build lines that span multiple lines via backslashes - When we hit a line ending with
\, we remove the backslash and keep adding to the buffer instead of yielding - Only when we hit a line that doesn't end with
\do we combine the buffer into a single complete line
- We use a buffer (
Comment Handling:
- Full comment lines: If a line starts with
#and we haven't started building a regular line (buffer is empty), we skip it entirely - Inline comments: Once we have a complete line, we split at the first
#and retain only the content before it - We strip trailing whitespace from processed lines to clean up any leftover spaces from comment removal
- Full comment lines: If a line starts with
Safe File Handling:
- Using a
withblock ensures the file is automatically closed after reading, even if an error occurs
- Using a
When run with your sample input, this code will produce exactly the ideal output you specified:
内容的提问来源于stack exchange,提问作者Jim T
相关产品推荐
相关产品推荐

