【问题标题】:A simple question about the indentation problem in txt关于txt中缩进问题的一个简单问题
【发布时间】:2023-03-10 06:23:01
【问题描述】:
def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    for j in range(len(re_doc2)):
        f2.write(re_doc2[j]+':'+def_lst[j])
    f2.close()

上面是类中的一个函数。另外,内容已经写在my_dic.txt中了。

A:Contents of B
B:Contents of B

我想通过上面的函数添加内容。但是这里有一个问题。我要把C到E的内容加进去,我希望的理想情况如下。

A:Contents of B
B:Contents of B
C:Contents of C
D:Contents of D
E:Contents of E

但是,如果我使用上面的函数,结果如下。

A:Contents of B
B:Contents of BC:Contents of C
D:Contents of D
E:Contents of E

我又试着写了一个转义码,但这次是这样。

def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    for j in range(len(re_doc2)):
        f2.write('\n'+re_doc2[j]+':'+def_lst[j])
    f2.close()

A:Contents of B
B:Contents of B
C:Contents of C

D:Contents of D

E:Contents of E

我对此感到很困扰。怎么解决?

【问题讨论】:

  • 您是否愿意接受有关如何以合理方式存储数据的建议?
  • 你需要从文件中读取最后一个字符并检查它是否是换行符,如果不是则写一个......

标签: python append


【解决方案1】:

您可以在向 f2 写入新行之前写一个 '\n'。

def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    f2.write('\n')
    for j in range(len(re_doc2)):
        f2.write(re_doc2[j]+':'+def_lst[j])
    f2.close()

感谢马蒂亚斯的评论。可以这样写:

def sav_dic(self):
    with open('my_dic.txt', 'a') as f2:
        f2.write('\n')
        for x, y in zip(re_doc2, def_lst):
            f2.write(f'{x}:{y}')
        

【讨论】:

  • 你用你的转义码让我逃离了任务的地狱!真的很感谢!
  • 你可能想用for value1, value2 in zip(re_doc2, def_lst):后跟f2.write(value1 + ':' + value2)(或f2.write(f'{value1}:{value2})之类的东西来改变这个非pythonic索引访问。当然你应该用更有意义的名字替换value1value2
【解决方案2】:

你只能为你写的第一行写换行

for j in range(len(re_doc2)):
    if j == 0:
        f2.write('\n')
    f2.write(re_doc2[j]+':'+def_lst[j])

或者更新写入my_dic.txt 的代码以始终以\n 结束行

【讨论】:

  • 感谢您将宝贵的时间花在我身上。真的很感谢!
猜你喜欢
  • 2011-03-20
  • 2011-03-06
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2021-05-23
相关资源
最近更新 更多