Python批量读取目录中.xvg文件并单独存储结果的实现方案
Batch Processing .xvg Files in Python
Got it, let's turn your single-file script into a batch processor that handles all .xvg files in your directory and saves each result separately. Here's how to do it step by step:
Step 1: Import Required Module
We'll use Python's built-in os module to list all .xvg files in your target directory—no extra installs needed.
Step 2: Full Batch Processing Code
This script will loop through every .xvg file, run your logic, and save each result to a matching output file (e.g., coord_1.xvg gets a coord_1.result file):
import os # Set the path to your folder with .xvg files xvg_directory = '/home/abc/xyz/coord/' # Get all .xvg files in the directory all_xvg_files = [file for file in os.listdir(xvg_directory) if file.endswith('.xvg')] for filename in all_xvg_files: # Build full path to the current .xvg file file_path = os.path.join(xvg_directory, filename) try: # Read the file (using context manager for safe file handling) with open(file_path, 'r') as f: dat = f.readlines() # Skip first 22 header lines (adjust this number if your files have different headers) dat1 = dat[22:] dat2 = [] # Process each line to split into values for line in dat1: split_line = line.split() if split_line: # Skip empty lines dat2.append(split_line) # Determine result (fixed logic from your original code) result = 'N' # Default to N if no conditions are met for entry in dat2: try: value = float(entry[1]) if value >= 9.5: result = 'P' break elif value <= 5.9: result = 'R' break except (IndexError, ValueError): # Skip lines with missing or invalid values continue # Create output filename (replace .xvg with .result) output_filename = os.path.splitext(filename)[0] + '.result' output_path = os.path.join(xvg_directory, output_filename) # Save the result to the output file with open(output_path, 'w') as out_file: out_file.write(result) print(f"Successfully processed: {filename} → {output_filename}") except Exception as e: print(f"Failed to process {filename}: {str(e)}")
Key Improvements & Notes
- Batch Handling: Automatically finds all .xvg files in your target folder, no need to list them manually.
- Safe File Operations: Uses
with open(...)to ensure files are properly closed after reading/writing, preventing data leaks. - Error Resilience: Added try-except blocks to handle issues like corrupted files, missing lines, or invalid numbers—so the script won't crash halfway through processing.
- Fixed Logic: Your original code would print 'N' for every line that didn't meet P/R conditions. This version sets a default 'N' and only updates it if it finds a line that triggers P or R (which I assume was your intended behavior).
How to Use
- Replace
xvg_directorywith the actual path to your .xvg files. - Adjust the
dat[22:]line if your files have more or fewer header lines. - Run the script—each .xvg file will get a corresponding
.resultfile containing its P/R/N value.
内容的提问来源于stack exchange,提问作者accidental_coder
相关产品推荐
相关产品推荐

