【问题标题】:Writing at different locations in a file: Python在文件的不同位置写入:Python
【发布时间】:2018-07-20 04:54:11
【问题描述】:

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

例如:
字典是{'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)

请帮忙。谢谢。

【问题讨论】:

  • 你有什么问题?
  • 我有一个现有文件,我有一个列表字典。我想在某些位置(在每个“测试 X”的末尾和下一个“测试 Y”之前)使用列表字典的内容更新我的文件。我怎样才能做到这一点?如果我不清楚,请道歉。
  • 通常在这里你给出你的问题,显示你已经必须解决它的代码,并明确说明什么不符合你的预期。 “如何……?”问题类型通常被认为是广泛的。
  • 您好,很抱歉我是第一次发帖,所以我不确定您是如何查看它的。但是我已经展示了我编写的代码并描述了问题。跨度>
  • 在处理这样的文件时尝试使用 with。 with open('Out.txt','w+') as f: # file read-write code

标签: python dictionary file-handling read-write


【解决方案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()

【讨论】:

  • 谢谢!这似乎适用于该示例。我将在我的代码中尝试并检查!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2023-03-23
  • 1970-01-01
  • 2022-09-27
  • 2016-09-10
  • 2013-12-06
  • 1970-01-01
相关资源
最近更新 更多