开发者社区> 问答> 正文

尝试从文件中读取并写入另一个文件。生成的文件为空

我有一个.fastq文件,我试图从中读取并生成其反向补码。运行我的脚本后,生成的文件为空。

这是Python 3.7。我正在使用函数rev_comp来完成此任务。这是我已编写的代码。

import gzip
import re

Reverse Complement Function

def rev_comp(dna):

dna_upper = dna.upper() #Ensures sequence is upper-case
dna_rev = dna[::-1] #Reverses the string

conversion = {'A':'T','C':'G','G':'C','T':'A','Y':'R','R':'Y',\
       'S':'S','W':'W','K':'M','M':'K','B':'V','V':'B',\
       'D':'H','H':'D','N':'N','-':'-'}

revcomp = ''

for i in dna_rev:
    revcomp += conversion[i]
    reverse = open("Script_result.txt", 'w')
    reverse.write(revcomp)

reverse.close()

"""

String finding function

def string_find(string):"""

x = input("Enter filename (with extension) of the DNA sequence: ")

if x.endswith(".gz"): #Condition for gzip files

with gzip.open(x, 'rb') as f:
    file_content = f.read()
    new_file = open("unzipped.fasta", 'w')
    new_file.write(str(file_content))
    print("unzipped.fasta written to directory")
    rev_comp(new_file)

with open(x, 'r') as xfile:

xread = xfile.readlines()
seq_string = ''
if x.endswith(".fasta"):   #condition for fasta files
    for i in xread:
        if not i.startswith('>'):
            seq_string = seq_string + i.strip('\n')

if x.endswith(".fastq"):        #condition for fastQ files
    for i in range(1,len(xread),4):
        seq_string = seq_string + xread[i].strip('\n')

rev_comp(seq_string)
我期待生成一个文本文件与fastq文件中的序列反向补充。但是,结果 Script_result.txt是空白的

展开
收起
一码平川MACHEL 2019-01-22 15:06:05 3005 0
1 条回答
写回答
取消 提交回答
  • 这是有缺陷的地区:

    revcomp = ''

    for i in dna_rev:

    revcomp += conversion[i]
    reverse = open("Script_result.txt", 'w')
    reverse.write(revcomp)

    每次以“w”模式打开文件时,都会清除文件。然后你要写一些东西才能再次清除它。打开它一次,with然后在with块下执行所有文件操作。我还注意到你revcomp每次都在添加并写出结果。这将导致如下文件:

    a
    ab
    abc
    abcd
    等等等等。我想你只是在寻找一条线abcd。revcomp要先进行计算,然后将最终结果写入文件。随着所有的变化:

    revcomp = ''.join(conversion[i] for i in dna_rev)

    with open("Script_result.txt", 'w') as f:

    f.write(revcomp)

    如果您不希望每次在a模式下打开时截断文件以附加结果,如下所示:with open("Script_result.txt", 'a') as f

    另外在这个块中:

    if x.endswith(".gz"): #Condition for gzip files

    with gzip.open(x, 'rb') as f:
        file_content = f.read()
        new_file = open("unzipped.fasta", 'w')
        new_file.write(str(file_content))
        print("unzipped.fasta written to directory")
        rev_comp(new_file)

    你要传入一个文件对象rev_comp。替换为rev_comp(file_content)

    最后一次调用rev_comp将导致此调用中的写入被清除。a如果要保存结果,请在模式下打开文件

    2019-07-17 23:26:17
    赞同 展开评论 打赏
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载