Python实现:搜索首字符为')'的行并删除其上一行的逗号
Solution to Remove Trailing Comma from Previous Line of
)-Starting Lines Got it, let's solve this problem with a straightforward Python script. The goal is to scan your file for lines that start with ), then remove the trailing comma from the line immediately above them.
Here's the Python code:
def fix_trailing_comma(file_path): # Read all lines from the file, preserving each line's content (minus newline chars) with open(file_path, 'r') as f: lines = [line.rstrip('\n') for line in f] # Iterate through lines starting from the second one (since we need to check the previous line) for i in range(1, len(lines)): current_line = lines[i] # Check if current line starts with ')' — uncomment the line below if you need to ignore leading whitespace # if current_line.lstrip().startswith(')'): if current_line.startswith(')'): # Remove any trailing comma from the previous line (handles cases with spaces before the comma too) lines[i-1] = lines[i-1].rstrip(', ') # Write the modified content back to the file (consider saving to a new file first for backup!) with open(file_path, 'w') as f: f.write('\n'.join(lines) + '\n') # Replace 'your_target_file.txt' with your actual file path fix_trailing_comma('your_target_file.txt')
Key details to keep in mind:
- Whitespace flexibility: If your lines might have leading spaces/tabs before the
), swap the condition tocurrent_line.lstrip().startswith(')')to ignore leading whitespace. - Backup first: Always make a copy of your original file before running the script—you can modify the write step to save to a new file (e.g.,
file_path + '_fixed.txt') instead of overwriting the original, just to be safe. - Clean comma removal: Using
rstrip(', ')ensures we remove both the comma and any trailing spaces right before it, so the line looks clean after modification.
Example before/after:
Original content:
xxxxxx PCTFREE 10 INITRANS 8 MAXTRANS 255 STORAGE ( BUFFER_POOL DEFAULT ), )
After running the script:
xxxxxx PCTFREE 10 INITRANS 8 MAXTRANS 255 STORAGE ( BUFFER_POOL DEFAULT ) )
内容的提问来源于stack exchange,提问作者Shaz
相关产品推荐
相关产品推荐

