python - 如何检查给定文件是否为 FASTA?

标签 python user-input

我正在设计一个需要在早期阶段之一输入 .fasta 文件的代码。现在,我正在使用此函数验证输入:

def file_validation(fasta):
    while True:
        try:
            file_name= str(raw_input(fasta))
        except IOError:
            print("Please give the name of the fasta file that exists in the folder!")
            continue

        if not(file_name.endswith(".fasta")):
            print("Please give the name of the file with the .fasta extension!")
        else:
            break
    return file_name

现在,虽然这个函数工作正常,但仍然存在一些错误的余地,因为用户可能输入一个文件,虽然文件名以 .fasta 结尾,但可能有一些非 .fasta里面的内容。我该怎么做才能防止这种情况发生并让用户知道他/她的 .fasta 文件已损坏?

最佳答案

为什么不把文件当作 FASTA 来解析,看看它是否会损坏?

使用 biopython ,它通过在非 FASTA 文件上返回一个空生成器而默默地失败:

from Bio import SeqIO

my_file = "example.csv"  # Obviously not FASTA

def is_fasta(filename):
    with open(filename, "r") as handle:
        fasta = SeqIO.parse(handle, "fasta")
        return any(fasta)  # False when `fasta` is empty, i.e. wasn't a FASTA file

is_fasta(my_file)
# False

关于python - 如何检查给定文件是否为 FASTA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293407/

相关文章:

java - 测试键盘输入的字符串是否具有有效的日期和格式

Python networkx加权图在最短路径计算中不考虑节点的权重?

Python doctest执行上下文

c++ - 无法轮询 SDL 中的鼠标单击事件

c# - winforms 应用程序如何在没有焦点的情况下接受用户输入?

java - 保存大量动态用户输入

python - 如果 python 出现错误,请用户重新输入

python - 给定一个单词列表和一个句子,找到整个句子或作​​为子字符串出现在句子中的所有单词

python - 在spark(python)中划分两个rdds的值

python - 在 cherrypy/mako 中使用动态参数处理 URL