【问题标题】:Opening python file with readlines() method使用 readlines() 方法打开 python 文件
【发布时间】:2019-04-25 03:03:11
【问题描述】:

此项目的文件夹包含一个纯文本文件,其中包含 fasta 格式的 DNA 序列 ('MYH7.fasta')。

完成下面的单元格以使用 readlines() 方法打开和读取文件,并将序列保存到名为 DNAsequence 的字符串中。

注意:要完成的部分用“...”表示。其他部分不应更改。

inFile = ...

DNAsequence = ''

for ... in ...:

 if not(">" in Line):

if (len(Line) > 0):

 DNAsequence = DNAsequence + Line

print(DNAsequence)

print(len(DNAsequence))

【问题讨论】:

  • 尝试使用可以由其他人执行的代码来改进您的问题。 minimal reproducible example
  • @DanielGL:但这不是问题。这是一个作业。

标签: python python-3.x python-requests jupyter-notebook


【解决方案1】:

我怀疑他们正在寻找的答案是

inFile = open("MYH7.fasta", "r").readlines()

在 Perl 中,连接代码是标准的(示例如下)。我在这里不确定,因为 inFile.readlines() 应该根据回车构造一个数组,并且您问题中的不变代码不允许使用它的功能。以下代码回答了您的问题,使文件句柄保持打开状态并省略了 readlines()。

#!/usr/local/bin/python3
inFile = open("MYH7.fasta", "r")

DNAsequence = ''

for Line in inFile:
    if not(">" in Line):
        if (len(Line) > 0):
            DNAsequence = DNAsequence + Line

print(DNAsequence)

print(len(DNAsequence))

Perl 版本展示了如何在一行中连接多个命令。

#!/usr/bin/perl
my $DNAsequence;
open (IN, "<MYH7.fasta");
while (my $line = <IN>){
    chomp $line;
    next if $line =~ m/>/;
    $line =~ m/[ACGT]{10}/i ? $DNAsequence .= $line : next;
   }
close IN;
print $DNAsequence, "\n", length($DNAsequence) . " and Python s\*\*ks\n";

MYH7.fasta 输入文件将是格式,

>example_sequence
ACGCGTAGACGTATAG

我认为您的代码中存在错误,因为如果回车符出现在序列中,它们将进入变量 DNAsequence。在 Perl 中,这些是使用 "chomp" 删除的,或者可以通过 $_ =~ s/\n// 显式删除(或者在此例如 $line =~ s/\n//;)。 “\n”的存在可能会使后续分析复杂化。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2011-06-20
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2023-01-26
    • 1970-01-01
    相关资源
    最近更新 更多