python - 将混合格式 .DAT 转换为 .CSV(或其他格式)

标签 python csv

我有大量 DAT 文件需要转换(最终转换为唯一的文件类型)。 DAT 的字段之间有混合数量的空白,并且列标题位于不同的行上。有什么建议吗?

                    ALT_RAD
                                               ALT_RAD2
                 DIRECT        D_GLOBAL        U_GLOBAL          Zenith
Year Mn Dy Hr Mi        DIFFUSE2            D_IR            U_IR
2004  9  1  0  1    1.04   79.40   78.67  303.58   61.06  310.95  85.142
2004  9  1  0  2    0.71   74.36   73.91  303.80   57.82  310.92  85.171
2004  9  1  0  3    0.67   71.80   71.64  304.25   56.84  310.98  85.199
2004  9  1  0  4    0.75   74.35   74.83  304.21   59.68  310.89  85.227

我有一个基本脚本:

import sys
with open(sys.argv[1], r) as input_file:
    newLines = []
    for line in input_file:
            newLines.append(newLine)

我肯定会更改它以解决混合空白,但我不知道如何使用不稳定的列标题。

最终我希望我的标题是:

Year Month Day Hour Minute Direct Diffuse2 D_Global D_IR U_Global U_IR Zenith

最佳答案

对输入文件中的那些标题行给予应有的蔑视。 (或者,换句话说,阅读它们并丢弃它们。)

headers='Year Month Day Hour Minute Direct Diffuse2 D_Global D_IR U_Global U_IR Zenith'
with open ( 'temp.dat') as input_file:
    with open ('temp_2.csv', 'w') as output_file:
        output_file.write('"%s"\n'%'","'.join(headers.split()))
        for count, line in enumerate(input_file):
            if count<4: continue
            outLine = ','.join(line.split())
            output_file.write(outLine + '\n')

关于python - 将混合格式 .DAT 转换为 .CSV(或其他格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269197/

相关文章:

python - Odoo : inputing employee based on department_id, one2many 域

python - 如何将列表拆分为大小相等的 block ?

python - (1054, "Unknown column ' 日期'在 'field list'")

java - 使用 Apache Spark (Java) 将 CSV 数据加载到 Dataframe 并转换为数组

python - 查找并写入列中的下一个空白单元格

python - 为 scrapy CrawlSpider 的方法创建单元测试

python - 如何在 Python 中创建动态范围变量?

python - 将 CSV 数据流转换为 Pandas DataFrame (Python 2.7)

vba - 使用 vba 将 excel 中的一系列数据导出为 ascii 纯文本格式的表格 csv 或 txt 文件

java - 使用java将多个csv文件合并为一个文件?