【问题标题】:Convert .txt file (data feed) to .csv file将 .txt 文件(数据馈送)转换为 .csv 文件
【发布时间】:2018-12-18 01:06:21
【问题描述】:

基本上原始数据没有标题,只有值(但我有标题列表)。分隔符是“|”。现在我尝试做的是通过使用将 txt 文件转换为 csv 文件。 csv 文件包含我拥有的标题和相应的值。

例如:

txt 文件看起来像:

sadasd|dsdads|adsasd

值 1|值 2|值 3|值 4|值 5|价值 100|价值 101|价值 102|值 103|值 104|值 105 值 200|值 201|值 202|值 203|值 204|值 205

sdasd|dsa|dsdad

转换后的 .csv 文件将如下所示:

标题1,标题2,标题3,标题4,标题5,

值 1,值 2,值 3,值 4,值 5,

值 100,值 101,值 102,值 103,值 104,值 105

值 200,值 201,值 202,值 203,值 204,值 205

我刚开始学习python,我的想法是什么:

  • 删除第一行和最后一行。

  • 使用字典列表:每一列都是一个带有键的列表(我有标题)。到数据框

  • 转换为 .csv

所以它看起来像 {'header 1': [value 1, value 100, value 200],'header 2': [value 2, value 101, value 201]。然后转换为 .csv。

这只是我的想法,或者你有最简单的方法,但只使用 python。

【问题讨论】:

  • 你知道是否总是正好有 5 个值吗?这会因文件而异吗?您是否尝试过查看其他删除 first 和 last 行的 SO 帖子?

标签: python text-parsing


【解决方案1】:

使用csv 模块

例如:

import csv
with open(filename, "r") as infile:
    data = []
    for i in infile.readlines()[1:-1]:                   #Strip first and last line. 
        if i.strip():
            data.extend(i.strip().split("|"))
data = [data[i:i+5] for i in range(0, len(data), 5)]     #Split list to sub-list of 5 elements
print(data)


header = ["header 1","header 2", "header 3", "header 4", "header 5"]
with open(outfile, "w") as outfile:                     #Output CSV file
    writer = csv.writer(outfile, delimiter=",")
    writer.writerow(header)                             #Write Header
    writer.writerows(data)                              #Write content.

【讨论】:

  • 嗨,Rakesh,感谢您的快速回复。如果在传输过程中,我想删除一些值列(比如说第 3 列和第 5 列),该怎么做。以及如何输出文件是 .csv 文件。
【解决方案2】:

从 stackoverflow 中的部分拼接得到以下解决方案

import pandas as pd

mycolnames = ['col1','col2','col3','col4','col5']

# Use the sep argument to change your delimiter accordingly
df = pd.read_csv("foo.txt", sep="|")

# Set your column names to the data frame
df.columns = mycolnames

# Write your desired columns to csv
df['col1'].to_csv("bar.csv", sep=",")

学分

@atomh33ls - How to read csv into record array in numpy?

@LangeHaare - set column names in pandas data frame from_dict with orient = 'index'

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多