【问题标题】:python create lists from multiple text files and create csv file from those listspython从多个文本文件创建列表并从这些列表创建csv文件
【发布时间】:2014-10-21 04:20:47
【问题描述】:

遇到一个树桩,我有两个旧文本文件,我想从中提取数据以创建一个 csv 文件。

为了简短起见,我的代码与屏幕上的代码完全相同:

import csv, itertools

list1 = []
with open('D:/py_files/legacy_temp/REPORT_1.TXT', 'rb') as tf:
    for line in tf:
        if len(line) > 2:
            if line[17].isdigit():
                acctnum = str(line[16:31])
                custname = str(line[39:58])
                currbal = str(line[84:96])
                diffbal = str(line[102:114])
                list1.append(acctnum + '|' + custname + '|' + currbal + '|' + diffbal)

list2 = []
with open('D:/py_files/legacy_temp/REPORT_2.TXT', 'rb') as tf2:
    for line in tf2:
        if line[0].isdigit():
            acctnum = str(line[1:12])
            ourbal = str(line[80:90])
            alldnum = str(line[123:131])
            clntnum = str(line[132:152])
            list2.append(acctnum + '|' + ourbal + '|' + alldnum + '|' + clntnum)

下面的代码只是我的剪贴簿,我正在尝试的东西。我可以创建 csv 文件,但它要么写为一个连续的长行,要么在附加“|”时写入在每个字符之后,即:a|b|c|d|等等……

#mlist = []
#if len(list1) == len(list2):
#   for i, j in map(None,list1,list2):
#       print i + '|' + j
def f1():
    clist = []
    outfile = csv.writer(open('D:/py_files/legacy_temp_/report_diff.csv', 'wb'))
    if len(list1) == len(list2):
        for i, j in map(None,list1,list2):
            clist.append(str(i + '|' + j + '\n'))
        outfile.writerow(clist)
        print '\n'.join(clist)

def f2():
    for x,y in zip(list1,list2):
        print list1+list2
def f3():
    output = list(itertools.chain(list1,list2))
    print '\n'.join(output)

两件事,a) 我是否以正确的方式进行此操作(分别打开两个文本文件),以及 b) 如果我是,我如何编写一个 csv 文件,该文件将为我提供以下行:

acctnum|custname|currbal|diffbal|acctnum|ourbal|alldnum|clntnum

将上面| 中的每个元素放在一个单独的单元格中..

PS。我只使用管道作为分隔符,因为余额中有逗号。我不需要使用管道,因为我可以替换天平中的逗号。

非常感谢所有帮助,谢谢

【问题讨论】:

    标签: python list csv text merge


    【解决方案1】:

    实际上,原始功能将与第二个功能一起使用,只需稍作修改:

    def f2():
        for x,y in zip(list1,list2):
            print list1+list2 <-- this should be print x+y
    

    【讨论】:

      【解决方案2】:

      应该把你想附加的东西放在括号里。

      list1.append([acctnum + '|' + custname + '|' + currbal + '|' + diffbal])
      

      你也可以这样做:

      list1.append(['|'.join([acctnum, custname, currbal, diffbal])])
      

      然后您将在 list1 中获得一堆列表,它们代表一行。

      【讨论】:

        【解决方案3】:

        如果您想以最快、最简单的方式将数据从 txt 转换为 csv,您可以执行以下操作:

        import csv
        
        header = ('acctnum,custname,currbal,diffbal,acctnum,ourbal,alldnum,clntnum\n')
        with open('out.csv', 'wb') as fout:
            fout.write(header)
        
            with open('blah1.txt', 'rU') as fin1:
                fin1.next()
        
                for row in fin1:
                    fout.write(row.replace('|',','))
        
            fout.write('\n')
        
            with open('blah2.txt', 'rU') as fin2:
                fin2.next()
        
                for row in fin2:
                    fout.write(row.replace('|',','))
        

        这将获取您的两个文件,并将它们合并为一个 CSV,同时处理管道分隔符。如果您已经删除了管道,那么只需删除“.replace('|',',') 位,这样你就只会将“行”传递给 csv 编写器。然后你可以删除你没有删除的任何其他列想要excel什么的。

        【讨论】:

          【解决方案4】:

          谢谢,缩进不当。

          import csv
          
          path = 'D:/py_files/legacy_temp/'
          
          outfile1 = csv.writer(open(path + 'REPORT_1.csv', 'wb'))
          with open(path + 'REPORT_1.TXT', 'rb') as f1:
              for line in f1:
                  lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
                  if len(lne) > 2:
                      if lne[17].isdigit():
                          list1 = []
                          list1.append(str(lne[16:31].replace('-','').strip()))
                          list1.append(str(lne[39:58].strip()))
                          list1.append(str(lne[84:96].strip()))
                          list1.append(str(lne[102:114].strip()))
                          outfile1.writerow(list1)
          
          outfile2 = csv.writer(open(path + 'REPORT_2.csv', 'wb'))
          with open(path + 'REPORT_2.TXT', 'rb') as f2:
              for line in f2:
                  lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
                  if len(lne) > 1:
                      if lne[0].isdigit():
                          list2 = []
                          list2.append(str(lne[1:12].strip()))
                          list2.append(str(lne[80:90].strip()))
                          list2.append(str(lne[123:131].strip()))
                          list2.append(str(lne[132:152].strip()))
                          outfile2.writerow(list2)
          

          现在我正在查看 csv 文件,我宁愿合并两个列表并创建一个 csv 文件。它们的长度总是相同的。如果不是,那么报告有问题。我将开始研究这个..

          编辑: 这里合并了吗……

          import csv
          
          path = 'D:/py_files/legacy_temp/'
          
          with open(path + 'REPORT_MERGE.csv', 'wb') as csvf1:
              writer = csv.writer(csvf1)
          
              lst1 = []
              with open(path + 'REPORT_1.TXT', 'rb') as f1:
                  for line in f1:
                      lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
                      if len(lne) > 2:
                          if lne[17].isdigit():
                              list1 = []
                              list1.append(str(lne[16:31].replace('-','').strip()))
                              list1.append(str(lne[39:58].strip()))
                              list1.append(str(lne[84:96].strip()))
                              list1.append(str(lne[102:114].strip()))
                              lst1.append(list1)
          
                              #creates ['x', 'x', 'x', 'x']
          
              lst2 = []
              with open(path + 'REPORT_2.TXT', 'rb') as f2:
                  for line in f2:
                      lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
                      if len(lne) > 1:
                          if lne[0].isdigit():
                              list2 = []
                              list2.append(str(lne[1:12].strip()))
                              list2.append(str(lne[80:90].strip()))
                              list2.append(str(lne[123:131].strip()))
                              list2.append(str(lne[132:152].strip()))
                              lst2.append(list2)
          
                              #creates ['y', 'y', 'y', 'y']
          
              for x, y in zip(lst1,lst2):
                  writer.writerow(x + y)
                  #creates ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y']
                  #each element in merged list writes to its own cell *****
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-09-17
            • 2013-07-27
            • 2011-05-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-22
            • 1970-01-01
            相关资源
            最近更新 更多