读取具有不同列数python的数据文件

时间:2013-05-18 15:03:18

标签: python

我有一个数据文件,前8行看起来像这样。 (取代实际后 为了这个问题的清晰度,用字母表示值)

    a,b,c
    d
    e,f
    g,h
    i,j,k
    l
    m,n
    o,p

这些代表有关电网中变压器的数据。前4 线是关于变压器1的信息,接下来的四个是变压器2 等等。

变量a-p可以是整数,浮点数或字符串

我需要在python中编写一个脚本,以便将一个变换器的数据分散到4行,而不是将它们全部放在一行上。

更准确地说,我希望将上述两行转换为

  a,b,c,d,e,f,g,h
  i,j,k,l,m,n,o,p

并将其写入另一个数据文件 我该怎么做?

4 个答案:

答案 0 :(得分:1)

如果总是4行(这行中的字段数不重要)是关于一件事的信息你可以这样做:

with open('your_data_file.txt', 'r') as i, open('output_file.txt', 'w') as o:
    new_info = 4
    for line in i:
        o.write(line.strip())  # use .strip() to remove new line character
        new_info -= 1
        if new_info == 0:
            o.write('\n')  # begin info of new transformer in new line
            new_info = 4
        else:
            o.write(',')  # write a , to separate the data fields, but not at
                          # the end of a line

在此代码中,输入和输出文件将被打开,并且输出的一行中的输入总是4行“转换”并写入。

答案 1 :(得分:1)

使用grouper recipe from itertools

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)


with open('z.t') as f:
    d = grouper(f, 4)
    for x in d:
            print ','.join(y.rstrip() for y in x) 

a,b,c,d,e,f,g,h
i,j,k,l,m,n,o,p

答案 2 :(得分:0)

假设此数据模式在整个输入文件中仍然存在......

首先,您需要读取包含数据的文件(filename是一个字符串;文件的路径)

f = open(filename, "r")   # open in read mode
content = f.read()        # read everything as one string
f.close()

一旦你以字符串(content)的形式阅读了文件的内容,只需收集所有数据,然后将其分开然后重新形成即可。

假设每个变压器与8个值相关联;

content = content.replace('\n', ',')   # put everything on one line
values = content.split(',')            # split it all up

lines = []
for i in range(0, len(values), 8):          # iterate by 8 elements
    lines.append(",".join(values[i:i+8]))   # merge these values and add to lines

output = "\n".join(lines)                   # merge these lines (via new lines)

然后,您将继续将输出写入文件;

f = open(newfile, "w")  # open the new file in write mode; it doesn't have to exist yet
f.write(output)
f.close()

答案 3 :(得分:0)

这个怎么样:

import itertools

# From itertools recipes
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

with open('output', 'w+') as fout:
    with open('filename') as fin:
        fout.writelines(','.join(tup) + '\n' for tup in
            grouper(itertools.chain.from_iterable(
                line.strip().split(',') for line in fin), 8, '-'))

这将所有行中的所有字段链接在一起作为单个可迭代,然后将它们分组为8个块,然后将它们写入新文件。

这个方法并不关心每行有多少列 - 它甚至可以在整个文件中改变。它只需要它们作为连续的8元组

相关问题