You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按DataFrame列表筛选并移动FASTA文件?

Can Python Move Specific FASTA Files Based on a DataFrame Column?

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 creation
  • shutil: For safely moving files
  • pandas: 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 .fasta instead of .fa, you can use glob to 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() with shutil.copy2() (this preserves file metadata like creation time).

内容的提问来源于stack exchange,提问作者Grendel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:39:47