【问题标题】:Using Python to Merge Single Line .dat Files into one .csv file使用 Python 将单行 .dat 文件合并为一个 .csv 文件
【发布时间】:2016-01-31 22:20:18
【问题描述】:

我是编程领域的初学者,想了解一些有关如何解决挑战的提示。 现在我有大约 10 000 个 .dat 文件,每个文件都有一行遵循这个结构:

Attribute1=Value&Attribute2=Value&Attribute3=Value...AttibuteN=Value

我一直在尝试使用 python 和 CSV 库将这些 .dat 文件转换为单个 .csv 文件。

到目前为止,我能够编写一些可以读取所有文件的东西,将每个文件的内容存储在新行中并将“&”替换为“”,但是由于 Attribute1,Attribute2...AttributeN 正是每个文件都相同,我想将它们制作成列标题并将它们从其他每一行中删除。

关于如何去做的任何提示?

谢谢!

【问题讨论】:

    标签: python csv


    【解决方案1】:

    由于您是初学者,我准备了一些有效的代码,同时非常容易理解。

    我假设您在名为“输入”的文件夹中拥有所有文件。下面的代码应该在文件夹旁边的脚本文件中。

    请记住,应使用此代码来了解如何解决此类问题。优化和健全性检查被故意忽略了。

    您可能还想检查当某行中缺少值时会发生什么、缺少属性时会发生什么、输入损坏时会发生什么等。:)

    祝你好运!

    import os
    
    # this function splits the attribute=value into two lists
    # the first list are all the attributes
    # the second list are all the values
    def getAttributesAndValues(line):
        attributes = []
        values = []
    
        # first we split the input over the &
        AtributeValues = line.split('&')
        for attrVal in AtributeValues:
            # we split the attribute=value over the '=' sign
            # the left part goes to split[0], the value goes to split[1]
            split = attrVal.split('=')
            attributes.append(split[0])
            values.append(split[1])
    
        # return the attributes list and values list
        return attributes,values
    
    # test the function using the line beneath so you understand how it works
    # line = "Attribute1=Value&Attribute2=Value&Attribute3=Vale&AttibuteN=Value"
    # print getAttributesAndValues(line)
    
    # this function writes a single file to an output file
    def writeToCsv(inFile='', wfile="outFile.csv", delim=","):
        f_in = open(inFile, 'r')    # only reading the file
        f_out = open(wfile, 'ab+')  # file is opened for reading and appending
    
        # read the whole file line by line
        lines = f_in.readlines()
    
        # loop throug evert line in the file and write its values
        for line in lines:
            # let's check if the file is empty and write the headers then
            first_char = f_out.read(1)
            header, values = getAttributesAndValues(line)
    
            # we write the header only if the file is empty
            if not first_char:
                for attribute in header:
                    f_out.write(attribute+delim)
                f_out.write("\n")
    
            # we write the values
            for value in values:
                f_out.write(value+delim)
            f_out.write("\n")
    
    # Read all the files in the path (without dir pointer)
    allInputFiles = os.listdir('input/')
    allInputFiles = allInputFiles[1:]
    
    # loop through all the files and write values to the csv file
    for singleFile in allInputFiles:
        writeToCsv('input/'+singleFile)
    

    【讨论】:

    • 非常感谢!如您所愿,这段代码帮助我解决了我的问题并给了我一些学习的东西。
    【解决方案2】:

    但由于 Attribute1,Attribute2...AttributeN 完全相同 对于每个文件,我想将它们变成列标题和 将它们从其他每一行中删除。

    input = 'Attribute1=Value1&Attribute2=Value2&Attribute3=Value3'
    

    第一个文件一次:

    ','.join(k for (k,v) in map(lambda s: s.split('='), input.split('&')))
    

    对于每个文件的内容:

    ','.join(v for (k,v) in map(lambda s: s.split('='), input.split('&')))
    

    也许你需要额外修剪字符串;不知道你的输入有多干净。

    【讨论】:

    • 好吧,这是一个有趣的方法!我会试试看,让你知道会发生什么。谢谢!
    【解决方案3】:

    将 dat 文件放在名为 myDats 的文件夹中。将此脚本与名为temp.txt 的文件一起放在myDats 文件夹旁边。您还需要您的output.csv。 [即,您将在同一文件夹中拥有output.csvmyDatsmergeDats.py]

    mergeDats.py

    import csv
    import os
    g = open("temp.txt","w")
    for file in os.listdir('myDats'):
        f = open("myDats/"+file,"r")
        tempData = f.readlines()[0]
        tempData = tempData.replace("&","\n")
        g.write(tempData)
        f.close()
    g.close()
    h = open("text.txt","r")
    arr = h.read().split("\n")
    dict = {}
    for x in arr:
        temp2 = x.split("=")
        dict[temp2[0]] = temp2[1]
    with open('output.csv','w' """use 'wb' in python 2.x""" ) as output:
        w = csv.DictWriter(output,my_dict.keys())
        w.writeheader()
        w.writerow(my_dict)
    

    【讨论】:

    • 谢谢!运行这个,我得到:'IOError: [Errno 2] No such file or directory:'1.dat''
    • 应该修复它,再试一次
    猜你喜欢
    • 2018-03-30
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多