在文件的不同位置编写:Python

时间:2018-07-20 04:54:12

标签: python dictionary file-handling read-write

我有一个列表字典,我想将列表内容写到文件中的不同位置。到目前为止,我尝试过的操作仅适用于前两个实例,即字典的前两个元素(我认为它适用于两个元素,因为一旦写入第一个实例,我便尝试将其写入不同的文件中)。我不能让它循环并在多个位置写。

例如:
字典是{'1':[a, b, c], '2': [c,d,e], '3': [g,h,i]}

文件内容为:

Test 1  
some content  
some more content  

Test 2  
some other content  
some more content

Test 3....and so on.  

我希望输出为:

Test 1  
some content  
some more content  
a  
b  
c  

Test 2  
some other content  
some more content  
c  
d  
e  

Test 3....and so on.  

我写的代码部分是(我在'xlim'中有字典,在'f'中打开了输入文件):

g = open('Out.txt','w+')  
for line in f.readlines():  
    p = ''  
    q = ''  
    if "TestCase_2\n" in line:  
        for m in range(len(xlim[1])):  
            p = xlim[1][m]  
            g.write(xlim[1][m])  
            g.write('\n')  
        g.write('\n\n')      
    p,q = q,line   
    g.write(p)  
    g.write(q)  
g.close() ##This writes for the first instance 

#This works for the 2nd instance but stops after that.
g = open('Out.txt')  
h = open('Out1.txt','w+')      
for i in range(2,n+1):  
    g.seek(0)  
    for line in g.readlines():  
        p = ''  
        q = ''  
        if "TestCase_2\n" not in line and 'TestCase_'+str(i+1)+'\n' in line:  
            #print('Yes')  
            for m in range(len(xlim[i])):  
                #p = xlim[i][m]  
                h.write(xlim[i][m])  
                h.write('\n')  
            h.write('\n\n')      

            #print (p)
        p,q = q,line  
        h.write(p)  
        h.write(q)

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试一下:

import re
import os

append = {'1':['a', 'b', 'c'], '2': ['c', 'd', 'e'], '3': ['g', 'h' , 'i']}

o = open("Out.txt", "w")

flag = False
with open("In.txt") as f:
    line = f.readline()
    o.write(line)
    while line:
        m = re.match("Test (\d)*", line)
        if m:
            flag = True
            test_id = m.group(1)

        line = f.readline()
        if flag:
            if line.strip() == "":
                [o.write(item + os.linesep) for item in append[test_id]]
                flag = False
        o.write(line)

o.close()
相关问题