Python:将间隔数据转换为CSV数据

Python:将间隔数据转换为CSV数据,python,Python,我认为有一个简单的Python解决方案,但我似乎无法以优雅的方式实现 我基本上是尝试获取3列间隔数据,截断顶部的几行,然后将3列数据重新存储为CSV文件。基本上用一个逗号分隔列字段 第列字段格式为:整数、浮点、浮点 我的尝试如下所示 谢谢你的帮助 [编辑:按照原始海报的要求打印前5行。]请正确设置张贴内容的格式。把这样一个无格式的混乱抛向公众是不获得帮助和否决选票的最好方法。谢谢你的帮助。它工作得很好。很抱歉,原来的帖子格式混乱。此网站上的新发布。谢谢你的反馈。 import csv """

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

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

第列字段格式为:整数、浮点、浮点

我的尝试如下所示

谢谢你的帮助



[编辑:按照原始海报的要求打印前5行。]

请正确设置张贴内容的格式。把这样一个无格式的混乱抛向公众是不获得帮助和否决选票的最好方法。谢谢你的帮助。它工作得很好。很抱歉,原来的帖子格式混乱。此网站上的新发布。谢谢你的反馈。
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)
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)
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()