如何使用 python 将 .dat 转换为 .csv?

How to convert .dat to .csv using python?

我有一个 file.dat 看起来像:

id       | user_id | venue_id | latitude  | longitude | created_at

---------+---------+----------+-----------+-----------+-----------------

984301   |2041916  |5222      |           |           |2012-04-21 17:39:01

984222   |15824    |5222      |38.8951118 |-77.0363658|2012-04-21 17:43:47

984315   |1764391  |5222      |           |           |2012-04-21 17:37:18

984234   |44652    |5222      |33.800745  |-84.41052  | 2012-04-21 17:43:43

我需要获取已删除空纬度和经度行的 csv 文件,例如:

id,user_id,venue_id,latitude,longitude,created_at

984222,15824,5222,38.8951118,-77.0363658,2012-04-21T17:43:47

984234,44652,5222,33.800745,-84.41052,2012-04-21T17:43:43

984291,105054,5222,45.5234515,-122.6762071,2012-04-21T17:39:22

我尝试这样做,使用下一个代码:

with open('file.dat', 'r') as input_file:
    lines = input_file.readlines()
    newLines = []
    for line in lines:
        newLine = line.strip('|').split()
        newLines.append(newLine)

with open('file.csv', 'w') as output_file:
    file_writer = csv.writer(output_file)
    file_writer.writerows(newLines)

但我还是得到了一个带有“|”的csv文件符号和空 latitude/longtitude 行。 错误在哪里? 一般来说,我需要在 DateFrame 中使用生成的 csv 文件,所以也许有一些方法可以减少操作的数量。

使用不带参数的 split() 将导致在 space 之后拆分 例如 "test1 test2".split() 结果为 ["test1", "test2"]

相反,试试这个:

newLine = line.split("|")

str.strip() 从字符串中删除前导和尾随字符。
您想要拆分 "|" 上的行,然后去除结果列表的每个元素:

import csv

with open('file.dat') as dat_file, open('file.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file)

    for line in dat_file:
        row = [field.strip() for field in line.split('|')]
        if len(row) == 6 and row[3] and row[4]:
            csv_writer.writerow(row)

也许最好使用 map() 函数而不是列表理解,因为它必须运行得更快。使用 csv 模块也可以轻松编写 csv 文件。

import csv
with open('file.dat', 'r') as fin:
with open('file.csv', 'w') as fout:
    for line in fin:
        newline = map(str.strip, line.split('|'))
        if len(newline) == 6 and newline[3] and newline[4]:
            csv.writer(fout).writerow(newline)

使用这个:

data = pd.read_csv('file.dat', sep='|', header=0, skipinitialspace=True)
data.dropna(inplace=True)
with open("filename.dat") as f:
    with open("filename.csv", "w") as f1:
        for line in f:
            f1.write(line)

这可用于将 .dat 文件转换为 .csv 文件

结合之前的答案,我为 Python 2.7:

编写了代码
import csv

lat_index = 3
lon_index = 4
fields_num = 6
csv_counter = 0

with open("checkins.dat") as dat_file:
    with open("checkins.csv", "w") as csv_file:
        csv_writer = csv.writer(csv_file)
        for dat_line in dat_file:
            new_line = map(str.strip, dat_line.split('|'))
            if len(new_line) == fields_num and new_line[lat_index] and new_line[lon_index]:
                csv_writer.writerow(new_line)
                csv_counter += 1

print("Done. Total rows written: {:,}".format(csv_counter))

这对我有用:

data = pd.read_csv('file.dat',sep='::',names=list_for_names_of_columns)

我使用了没有 pre-processing 数据的标准 python 特征。我从之前的一个答案中得到了一个想法并对其进行了改进。如果数据头包含空格(CSV中经常出现这种情况),我们应该自己确定列名,并跳过带头的第1行。 之后,我们可以仅通过特定列删除 NaN 值。

data = pd.read_csv("checkins.dat", sep='|', header=None, skiprows=1,
                   low_memory = False, skipinitialspace=True,
                   names=['id','user_id','venue_id','latitude','longitude','created_at'])
data.dropna(subset=['latitude', 'longitude'], inplace = True)