python将字符串s写入文件_Python使用s写入文件

我是Python的初学者,正在尝试各种方法来完成简单的任务,即反向补充DNA或RNA序列来学习一些字符串函数等。我最新的方法几乎可以工作,但对于一个小的刺激,我找不到答案,可能是因为我正在使用的东西我不能正确理解。

我的函数是用来写一个空白文件的(这很管用!)然后打开一个包含序列的文件,一次循环一个字符,把它的反向补码写到新文件中。代码如下:def func_rev_seq(in_path,out_path):

"""

Read file one character at a time and retrun the reverse complement of each nucleotide to a new file

"""

# Write a blank file (out_path)

fb = open(out_path,"w")

fb.write("")

fb.close()

# Dictionary where the key is the nucleotide and the value is its reverse complement

base = {"A":"T", "C":"G", "G":"C", "T":"A", "a":"t", "c":"g", "g":"c", "t":"a", "k":"m", "m":"k", "y":"r", "r":"y", "b":"v", "v":"b", "d":"h", "h":"d", "K":"M", "M":"K", "Y":"R", "R":"Y", "B":"V", "V":"B", "D":"H", "H":"D", "U":"A", "u":"a"}

# Open the source file (in_path) as fi

fi=open(in_path,"r")

i = fi.read(1)

# Loop through the source file one character at a time and write the reverse complement to the output file

while i != "":

i = fi.read(1)

if i in base:

b = base[i]

else:

b = i

with open(out_path, 'r+') as fo:

body = fo.read()

fo.seek(0, 0)

fo.write(b + body)

fi.close()

fo.close()

问题是,当我运行函数时,输出文件中的字符串首先被一个字符截断,然后在我不想要的空行下面。

screen shot of input and output file examples

据我所知,带有(0,0)的seek函数应该指向文件的开头,但我可能误解了。

非常感谢任何帮助,谢谢!在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值