如何用Python按DataFrame列表筛选并移动FASTA文件?
Absolutely—Python has all the tools you need to handle this file-moving task without relying on external commands. Let me walk you through a reliable, easy-to-follow solution that accounts for common edge cases like missing files or existing target files.
Step-by-Step Breakdown
First, we'll use three key libraries:
os: For handling file paths and directory creationshutil: For safely moving filespandas: To work with your DataFrame (assuming you already have this imported)
1. Set Up Your Paths
Start by defining the source folder where all your FASTA files live, and the target folder where you want to move the selected files. We'll also make sure the target folder exists (Python will create it if it doesn't):
import os import shutil import pandas as pd # Replace these with your actual file paths source_directory = "/path/to/your/fasta_folder" target_directory = "/path/to/your/new_selected_fastas" # Create target directory if it doesn't exist (no error if it does) os.makedirs(target_directory, exist_ok=True)
2. Extract Selected Sequence Names from Your DataFrame
Grab the list of sequence names from your seq_names column, then generate the corresponding FASTA filenames by appending the .fa suffix:
# Assume your DataFrame is named 'df' selected_seq_names = df['seq_names'].tolist() # Convert sequence names to full FASTA filenames (e.g., "seq1" → "seq1.fa") selected_fasta_files = [f"{seq}.fa" for seq in selected_seq_names]
3. Move the Files (With Error Handling)
Loop through each selected file, check if it exists in the source directory, then move it. We'll add error handling to catch issues like missing files or permission errors:
for fasta_file in selected_fasta_files: # Build full paths for source and target (avoids cross-platform path issues) source_path = os.path.join(source_directory, fasta_file) target_path = os.path.join(target_directory, fasta_file) # Only attempt to move if the source file exists if os.path.exists(source_path): try: shutil.move(source_path, target_path) print(f"Successfully moved: {fasta_file}") except Exception as e: print(f"Failed to move {fasta_file}: {str(e)}") else: print(f"Warning: {fasta_file} not found in source directory")
Extra Tips for Robustness
- Handle Mixed Suffixes: If some files use
.fastainstead of.fa, you can useglobto find matching files instead of hardcoding the suffix. - Prevent Overwrites: If you don't want to overwrite existing files in the target folder, add a check for
os.path.exists(target_path)before moving, and skip or rename the incoming file. - Copy Instead of Move: If you want to keep the original files and make copies instead, replace
shutil.move()withshutil.copy2()(this preserves file metadata like creation time).
内容的提问来源于stack exchange,提问作者Grendel

