python在文件中写入_在文件中的不同位置写入:python

我有一本列表字典,我想把列表的内容写到一个文件中的不同位置。到目前为止,我所尝试的只适用于前两个实例,即字典的前两个元素(我认为它适用于两个元素,因为在第一个实例被写入后,我试图将其写入另一个文件)。我不能让它在多个位置循环和写入。

例如:

口述是

{'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)

请帮忙。谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值