【问题标题】:How to append a new line to a list in python?如何在python中的列表中添加新行?
【发布时间】:2020-08-07 17:38:26
【问题描述】:

我正在尝试在 python 的列表中添加新行以向我的文本文件写入任何建议?

header = ['Employee ID','Type','Routing Number','Account Number']
header.append("\n")

strOtherLine = [strSsn,strThisType,strThisRoute,strThisAcct]       
header.append("\n" + strOtherLine)

fc_otherfile  = r"c:\******\*****\gah\\" + strOtherSavedFile
#===Writing to the text file
with open(fc_otherfile,'w', newline='') as t:
    dirdep = csv.writer(t, delimiter="\t")
    dirdep.writerow(header)

这是我在文本文件中得到的:

 Employee ID    Type    Routing Number  Account Number  ""  ['###########', 'Checking', '###########','###########']    ['###########', 'Checking', '###########', '###########']   

但我想要的是这样的:

 Employee ID    Type    Routing Number  Account Number  
 ###########  Checking  ###########  ###########
 ###########  Checking  ###########  ###########
 

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    只需使用' '.join() 创建一个列表字符串。每当附加行之后使用 obj.write('\n') 。

    Example: Using text file.
    
    MyData = ['I', 'am', 'fine']
    line1 = '    '.join(MyData)
    
    with open('file.txt', 'a+') as data:
        data.write(line1)
        data.write('\n')
    

    【讨论】:

      【解决方案2】:

      当你应该使用字符串时,你正在使用列表:

      header = 'Employee ID\tType\tRouting Number\tAccount Number'
      header += "\n"
      
      strOtherLine = strSsn +'\t'+ strThisType +'\t'+ strThisRoute +'\t'+ strThisAcct       
      header += "\n"+ strOtherLine
      
      fc_otherfile  = r"c:\******\*****\gah\\" + strOtherSavedFile
      #===Writing to the text file
      with open(fc_otherfile,'w', newline='') as t:
          t.write(header)
      
      #confirm write was successful
      with open(fc_otherfile,'r') as t2:
           print(t2.read()) 
      

      【讨论】:

      • 我的文本文件现在看起来像这样 --E m p l o y e e 制表符在字符之间留有空格
      • 它仍然在我的文本文件中的一行
      • 令人费解。我添加了更多代码来回答。请重试。
      • 我的意思是它可以在 python 打印函数中按我想要的方式工作,但是当我打开我的文本文件时,它仍然在同一行上,我认为新的换行符不起作用跨度>
      • 好的 - 所以这是其他一些没有正确加载的代码(或编辑器)?
      【解决方案3】:

      如果你喜欢循环,你可以尝试这样的事情:

      toinsert = ""
      for each in header:
          toinsert.append(str(each)+"\t")
      toinsert.rstrip()  #remove trailing "\t"
      toinsert += "\n"
      
      for each in strOtherLine:
          toinsert.append(str(each)+"\t")
      toinsert.rstrip()
      toinsert += "\n"
      
      with open('file.txt', 'a+') as data:
          data.write(toinsert)
      

      【讨论】:

        猜你喜欢
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        相关资源
        最近更新 更多