2014-04-24 32 views
-1

在這裏我做了一個簡單的程序,通過一個文本文件,其中包含一些細菌基因組中的基因,包括編碼這些基因的氨基酸(明確使用更合適?)我非常依賴Biopython中的模塊。無法使用打印語句寫入文件

這在我的Python shell中運行良好,但我無法將它保存到文件中。

這工作:

import Bio 
from Bio import SeqIO 
from Bio.Seq import Seq 
from Bio.Alphabet import IUPAC 
from Bio.SeqUtils import GC 
from Bio.SeqUtils import ProtParam 
for record in SeqIO.parse("RTEST.faa", "fasta"): 
    identifier=record.id 
    length=len(record.seq) 
    print identifier, length 

但這並不:

import Bio 
from Bio import SeqIO 
from Bio.Seq import Seq 
from Bio.Alphabet import IUPAC 
from Bio.SeqUtils import GC 
from Bio.SeqUtils import ProtParam 
for record in SeqIO.parse("RTEST.faa", "fasta"): 
    identifier=record.id 
    length=len(record.seq) 
    print identifier, length >> "testing.txt" 

也不是這:

import Bio 
from Bio import SeqIO 
from Bio.Seq import Seq 
from Bio.Alphabet import IUPAC 
from Bio.SeqUtils import GC 
from Bio.SeqUtils import ProtParam 
f = open("testingtext.txt", "w") 
for record in SeqIO.parse("RTEST.faa", "fasta"): 
    identifier=record.id 
    length=len(record.seq) 
    f.write(identifier, length) 

也不是這:

import Bio 
from Bio import SeqIO 
from Bio.Seq import Seq 
from Bio.Alphabet import IUPAC 
from Bio.SeqUtils import GC 
from Bio.SeqUtils import ProtParam 
f = open("testingtext.txt", "w") 
for record in SeqIO.parse("RTEST.faa", "fasta"): 
    identifier=record.id 
    length=len(record.seq) 
    f.write("len(record.seq) \n") 
+2

你說他們不工作;他們在做什麼? – jonrsharpe

+2

前兩個不會打印到文件,因爲第一個將打印到stdout,而'>>是在python中的一個位移操作。其他兩種方法應該。請注意,示例代碼的最後一行將'len(record.seq)\ n'寫入您的文件,而不是數字的實際長度。你有什麼錯誤嗎? – msvalkon

+0

@msvalkon第三個會崩潰,因爲f.write只接受一個必須是字符串的參數。 嘗試f.write('{0},{1}'.format(identifier,length))。另外,不要忘記關閉文件(或與之一起使用)。 – AMacK

回答

3

你的問題是寫在一般的文件。

幾個樣品:

fname = "testing.txt" 
lst = [1, 2, 3] 
f = open(fname, "w") 
    f.write("a line\n") 
    f.write("another line\n") 
    f.write(str(lst)) 
f.close() 

f.write需要字符串作爲要寫入的值。

做同樣的使用情況管理器(這似乎是最Python化,學習這種模式):

fname = "testing.txt" 
lst = [1, 2, 3] 
with open(fname, "w") as f: 
    f.write("a line\n") 
    f.write("another line\n") 
    f.write(str(lst)) 

# closing will happen automatically when leaving the "with" block 
assert f.closed 

你也可以使用所謂的印刷字形語法(對於Python 2.x的)

fname = "testing.txt" 
lst = [1, 2, 3] 
with open(fname, "w") as f: 
    print >> f, "a line" 
    print >> f, "another line" 
    print >> f, lst 

print在這裏做了一些額外的事情 - 在最後添加換行符並將非字符串值轉換爲字符串。

在Python 3.x的印刷有不同的語法,因爲它是普通函數

fname = "testing.txt" 
lst = [1, 2, 3] 
with open(fname, "w") as f: 
    print("a line", file=f) 
    print("another line", file=f) 
    print(lst, file=f) 
+0

謝謝,你的正確,這會給我一些通用的文件知道如何 - 我掛上的東西是如何讓我的輸出寫入,(而不是我手動輸入的東西)。就我而言,這將是一個標識符,長度爲幾百個基因,全部在一個.fasta文件中找到。輸出工作正常,只是打印,列表只是向下滾動屏幕......但我不知道如何將其保存到文件!我很抱歉,我知道這可能是非常簡單和基本的,但我很新,這個網站被證明是一個很好的資源。 – Jackie

+1

@Jackie你想打印你的變量中的一些數據,可能是在一些循環中生成的。因此,您首先將變量轉換爲一個字符串,然後將其放入一個文件中,然後調用'f.write(that_string)'或使用另一種方法,如上所示。 –