import tkinter as tk from tkinter import filedialog, messagebox import re def process_file(): root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( title="Select a file to process", filetypes=[("Text files", "*.txt"), ("HTML files", "*.htm *.html"), ("All files", "*.*")] ) if not file_path: print("No file selected") return # Read the file with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Simple regex approach - only add p tags to text not already in tags # This preserves existing tags exactly as they are # Split by lines and process lines = content.split('\n') result_lines = [] in_tag = False for line in lines: # Check if line has any HTML tags if re.search(r'<[^>]+>', line): # Line has tags, keep as is result_lines.append(line) in_tag = True else: # Plain text line if line.strip(): result_lines.append(f'

{line.strip()}

') else: result_lines.append('') result = '\n'.join(result_lines) # Ask for confirmation to overwrite if not messagebox.askyesno("Confirm Overwrite", f"This will overwrite:\n{file_path}\n\nContinue?"): print("Operation cancelled") return # Overwrite the source file with open(file_path, 'w', encoding='utf-8') as f: f.write(result) print(f"✅ File overwritten: {file_path}") if __name__ == "__main__": process_file()