【问题标题】:python file-handling formattingpython文件处理格式
【发布时间】:2020-08-27 07:11:15
【问题描述】:

请帮忙,我有一本字典,我需要将其写入 txt 文件,我需要更改 dic 的格式,以便在写入新文件时可以在下面获得所需的输出。谢谢!

我的听写:

sdata = {'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}

当前输出:

{'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}

如何将其保存为以下格式而不是上述格式的文件?

期望的输出:

 A, 1 2 3 4
 
 B, 128 118
 
 C, 5 6 7
 
 D, 1 3 4

以下是我的代码:

def saveAndExit(sdata, x, r):
    outFileName = "updated.txt"
    outfile = open(outFileName, "w")
    print (f'Content of xxx after updated {x} was added to key{r}:')
    print (f'Content of xxx after updated {x} was added to key{r}:',file=outfile)
    print (sdata) # wrong format
    print (sdata, file=outfile)
    outfile.close()

【问题讨论】:

    标签: python dictionary file-handling


    【解决方案1】:

    以下应该做你想要的:

    for key, value in sdata.items():
        print(key + ", " + " ".join(str(v) for v in value))
    

    这会产生以下内容:

    A, 1 2 3 4
    B, 128 118
    C, 5 6 7
    D, 1 3 4
    

    如果你想将输出加倍,每行数据之间有空行(如帖子所示),只需添加:

    print()
    

    到循环。

    【讨论】:

      【解决方案2】:

      我会在print 中使用解包运算符 (*) 来获得所需的结果,方法如下:

      sdata = {'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}
      for key, value in sdata.items():
          print(f'{key},', *value, end='\n\n')
      

      输出:

      A, 1 2 3 4
      
      B, 128 118
      
      C, 5 6 7
      
      D, 1 3 4
      

      提供 '\n\n' 作为最终结果以获得空白行。

      【讨论】:

        【解决方案3】:

        试试这个:

        print('\n\n'.join("%s, %s" % (k,str(sdata[k]).strip("[]").replace(",","")) for k in sdata.keys()))
        

        以上内容将确保键从括号和逗号中删除。如果你愿意,你可以省略那些。

        输出:

        A, 1 2 3 4
        
        B, 128 118
        
        C, 5 6 7
        
        D, 1 3 4
        

        【讨论】:

          猜你喜欢
          • 2023-03-25
          • 2020-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-14
          • 1970-01-01
          • 2017-06-18
          • 1970-01-01
          相关资源
          最近更新 更多