[英]Need to assign information from the result of one function to the beginning of another
在這個項目中,我必須首先將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鏈為:”,並且不會返回任何鏈。
問題在於,一旦您寫入文件,光標就會被設置到文件的末尾,因此它什么也沒讀。 在complement = wf.read()
之前使用wf.seek(0)
,它應該可以工作。
通常,您應該使用這樣的全局文件對象-這很麻煩。 另外,除非必要,否則避免使用r+
,這可能會有些棘手。 您確實應該將使用的文件包裝在with
塊中:
例如,在頂部使用:
with open('dnafile.txt', 'r+') as df:
DNA = df.read()
這樣可以確保在塊末尾關閉文件。 請注意,您從未關閉過文件,這是一個壞習慣(實際上,它不會影響此處的任何內容)。
最后,使用文件在同一腳本中的函數之間進行通信沒有任何意義。 只需從一個函數return
適當的值,然后將其輸入另一個函數即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.