Python:间隔数据到CSV数据

时间:2011-03-01 17:25:59

标签: python

我认为有一个简单的Python解决方案,但我似乎无法以优雅的方式实现目标。

我基本上试图获取3列间隔数据,从顶部截断几行,然后将3列数据重新存储为CSV文件。基本上用一个逗号分隔列字段。

列字段格式为:integer,float,float

我的尝试如下所示。

非常感谢你的帮助。


import csv
""" assume list1.txt data file looks like this:

1    1.12      3.1456756
2    1.123     3.145675
3    1.1234    3.14567
4    1.12345   3.1456
5    1.1234    3.145
6    1.123     3.1456
7    1.12      3.14567
8    1.1       3.145675
9    1.12      3.1456756
10   1.123     3.14567568

"""
# read the data file in as a list
fin = open( 'list1.txt', "r" )
data_list = fin.readlines()
fin.close()

# REPRODUCE THE LINES 1 THRU 5 OF THE ORIGINAL FILE
print data_list[:5]
print '-'*60

# remove LINES 1 THRU 5 FROM THE READ IN DATA LIST
del data_list[:5]

# PRINT FIRST 5 LINES OF THE NEW DATA LIST
print data_list[:5]

# write the changed data (list) to a file
fout = open("list2.txt", "w")
fout.writelines(data_list)
fout.close()

# write the changed data (list) to a CSV.file
csv_in = csv.reader(open('list2.txt', 'rb'), delimiter=' ')
csv_out = csv.writer(open('list3.csv', 'wb'), delimiter=',')
for line in csv_in:
    csv_out.writerow(line)

2 个答案:

答案 0 :(得分:0)

import csv

with open('list1.txt') as inf:
    data_list = []
    for line in inf:
        try:
            i, f1, f2 = line.strip().split()
            data_list.append((int(i), float(f1), float(f2)))
        except ValueError:
            pass  # could not parse line

# REPRODUCE THE LINES 1 THRU 5 OF THE ORIGINAL FILE
print data_list[:5]
print '-'*60

# remove LINES 1 THRU 5 FROM THE READ IN DATA LIST
del data_list[:5]

# PRINT FIRST 5 LINES OF THE NEW DATA LIST
print data_list[:5]

# write the changed data (list) to a file
with open("list.csv", "w") as outf:
    csv.writer(outf).writerows(data_list)

答案 1 :(得分:0)

fin = open( 'list1.txt', "r" )
lines = fin.readlines()
fin.close()

# print the first 5 lines of the file
print lines[:5]
print '-'*60

data_list = []
for row in lines:
    # the following will skip over lines containing only white space
    if row.strip():
        continue
    # split row on white space
    items = row.split()
    data_list.append(int(items[0]), float(items[1]), float(items[2]))

# Do this instead of using del.
data_list = data_list[5:]

fout = open("list2.txt", "w")
fout.writelines(data_list)
fout.close()

[编辑:修改它以打印前5行作为原始海报请求。]