如何批量处理列表中XML文件以生成无空白行的新文件?
Batch Process XML Files to Remove Empty Lines
Got it, let's get that batch processing working for you! Your single-file logic is solid—we just need to wrap it in a loop that iterates over every XML file in your directory, and handle paths dynamically so each file gets processed correctly.
Here's the complete working code:
import os # Define your input and output directories input_dir = r'C:\Users\Max12\Desktop\xml\pdfminer\UiPath\output' output_dir = r'C:\Users\Max12\Desktop\xml\pdfminer\UiPath\out' # Ensure the output directory exists (creates it if it doesn't) os.makedirs(output_dir, exist_ok=True) # Loop through all files in the input directory for filename in os.listdir(input_dir): # Only process XML files to avoid handling non-XML items if filename.endswith('.xml'): # Build full paths for input and output files (safer than hardcoding) input_file_path = os.path.join(input_dir, filename) output_file_path = os.path.join(output_dir, filename) # Apply your empty-line removal logic to each file with open(input_file_path, 'r') as infile, open(output_file_path, 'w') as outfile: for line in infile: # Skip lines that are empty after stripping whitespace if not line.strip(): continue outfile.write(line) # Optional: Print status to track progress print(f"Successfully processed: {filename}")
Key improvements over your single-file code:
- Dynamic path handling: Using
os.path.join()ensures your code works across different operating systems (no more worrying about backslashes vs slashes) and avoids errors from hardcoded filenames. - Output directory safety:
os.makedirs(..., exist_ok=True)creates the output folder if it doesn't exist, so you won't get a "file not found" error when trying to write the cleaned files. - File filtering: The
filename.endswith('.xml')check ensures we only process XML files, ignoring any other files or subdirectories that might end up in your input folder. - Batch iteration: The loop runs through every qualifying file, so you'll get 4 cleaned XML files (one for each input file) in your
outdirectory, each with no empty lines.
Just run this code, and it'll handle all your XML files automatically!
内容的提问来源于stack exchange,提问作者Max FH
相关产品推荐
相关产品推荐

