我正在设计一个需要在早期阶段之一输入 .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/