2014-02-17 129 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])