我有一个时髦的制表符分隔的文件,我想使不那么时髦

2024-10-16 20:44:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多以制表符分隔的数据,这些数据被组织成多行,并且应该都在两行中。现在看起来是这样的:

    Some Key    Other key   Foo Key    Bar Key
     0           5           18         12

    More Key    Dor key     Gee Key    Francis Scott  Key
     19          14          8          0

    Wa Key      Whis key    Don Key    Luh Key
     0           2           8          16

我需要它看起来像这样:

    Some Key    Other key   Foo Key    Bar Key    More Key    Dor key     Gee Key    Francis Scott  Key    Wa Key      Whis key    Don Key    Luh Key
     0           5           18         12         19          14          8          0                    0           2           8          16

我有几百个csv文件,每个文件大约有20行,30列,所以我想尽可能多地编写脚本。我正在使用Python CSV,但我不知道如何向它解释我自己。你知道吗


Tags: 数据keyfoomorebarsomescottother
2条回答

您可以使用制表符作为分隔符拆分文件的内容,将每个int“eger元素放入一个数组,将每个string元素放入另一个数组。然后,将所有字符串(键)放在一行中,用制表符分隔,一行包含所有整数,用制表符分隔。你知道吗

这应该做到:

import csv
import sys

keys = []
values = []

reader = csv.reader(sys.stdin, delimiter="\t")
for row in reader:
    keys.extend(row)
    values.extend(next(reader))

    # skip empty line
    assert next(reader, []) == []

writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerow(keys)
writer.writerow(values)

另存为thingie.py公司并用python thingie.py < sample.csv(where)运行它示例.csv“是您的数据文件)

相关问题 更多 >