2014-02-17 138 views
-1

我想知道是否有重新安排在一個文件中的行的方式:重新排序行文件

我有一些原子座標文件,在一條線上的每個原子,我需要一些原子寫在別人面前。假設:

atom c1 
atom c2 
atom c3 

我需要重新排序行數。例如:

atom c2 
atom c1 
atom c3 

有沒有辦法做到這一點沒有列表?

即使創建一個列表,我沒有成功。最後的審判是:

i = open("input.pdb", "r") 
o = open("output.pdb", "w") 
l = [] 
for line in i: 
    l. append(line.split()) 
    for line in l: 
     if "atom c2" in line: 
     a = l.index(line) 
     b = int(a) -1 
     l[a] = l[b] 
for line in l: 
    0.write("{}\n".format(line)) 
o.close() 
os.remove("input.pdb") 

任何想法?

+0

你應該發佈整個家庭作業練習 – leon

+0

'0.write'?你的意思是'o.write'? – Blorgbeard

+0

如果這是您的代碼縮進的方式,那麼if:原子c2在行中:block是空的,其後的所有代碼將始終執行。 – IanAuld

回答

1

比方說,你既然沒有給出其他指示,你事先知道什麼順序線應該被寫入。

atom c1 # line 0 
atom c2 # line 1 
atom c3 # line 2 

在你的榜樣,那將是1, 0, 2。然後,而不是for line in l(另外,never name a variable "l"!),你可以反過來遍歷你的行索引列表,並寫每個相應的行。

with open("input.pdb", "r") as infile: 
    lines = [line for line in infile] # Read all input lines into a list 

ordering = [1, 0, 2] 
with open("output.pdb", "w") as outfile: 
    for idx in ordering: # Write output lines in the desired order. 
     outfile.write(lines[idx])