在这个项目中,我必须首先将DNA链转换成补体,我已经成功地创建了这个函数,但是我需要将这个函数的结果分配给下一个函数,以将其转换为RNA。我目前正在将结果发送到一个文件中,并试图将其导入到下一个函数,但它没有获取任何信息,我希望您能给我提供任何建议,谢谢!
#open file with DNA strand
df = open('dnafile.txt','r')
#open file for writing all new info
wf = open('newdnafile.txt', 'r+')
#function for finding complementary strand
def encode(code,DNA):
DNA = ''.join(code[k] for k in DNA)
wf.write(DNA)
print('The complementary strand is: ' + DNA)
#carrying out complement function
code = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
DNA = df.read()
encode(code,DNA)
#function for turning complementary strand into RNA
def final(code, complement):
for k in code:
complement = complement.replace(k,code[k])
wf.write('the RNA strand is: ' + complement + '\n')
print('the RNA strand is: ' + complement)
#carrying out RNA function
code = {'T':'U'}
#following line is where the issue arises:
complement = wf.read()
final(code,complement)每次我执行这个操作时,它都会打印“RNA链是:”而不能返回任何一条链。
发布于 2016-10-25 02:10:12
问题是,一旦写入文件,光标就被设置为文件的末尾,因此它没有读取任何内容。在complement = wf.read()使用wf.seek(0)之前,它应该可以工作。
通常,您应该使用这样的全局文件对象--这是自找麻烦。另外,除非有必要,否则不要使用r+,这可能有点棘手。您确实应该将文件的使用包装在with块中:
例如,在最高用途:
with open('dnafile.txt', 'r+') as df:
DNA = df.read()这将确保在块末尾关闭该文件。请注意,您从未关闭您的文件,这是一个坏习惯(它不会影响任何东西,真的)。
最后,使用文件在同一脚本中的函数之间进行通信是没有意义的。只需从一个函数中return适当的值并将其输入另一个函数即可。
https://stackoverflow.com/questions/40230154
复制相似问题