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

新手上路,请多包涵

我有一个 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文件符号和空纬度/经度行。错误在哪里?一般来说,我需要在 DateFrame 中使用生成的 csv 文件,所以也许有一些方法可以减少操作的数量。

原文由 Alex Savin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 887
2 个回答

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)

原文由 Eugene Yarmash 发布,翻译遵循 CC BY-SA 4.0 许可协议

用这个:

 data = pd.read_csv('file.dat', sep='|', header=0, skipinitialspace=True)
data.dropna(inplace=True)

原文由 Artem Shakurov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏