2011-03-01 52 views
0

我認爲有一個簡單的Python解決方案,但我似乎無法以優雅的方式到達那裏。Python:間隔數據到CSV數據

我基本上試圖採取3列的間隔數據,截斷頂部幾行,然後重新存儲爲CSV文件的3列數據。基本上用一個逗號分隔列字段。

列字段的格式將是:整數,浮點數,浮

我嘗試如下所示。

非常感謝您的幫助。


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

請正確格式化您的帖子。把這樣一個沒有格式化的混亂投入到公衆面前是不獲得幫助和反對票的最佳方式。 – 2011-03-01 17:28:01

+0

謝謝你的幫助。它工作得很好。對不起原來的文章格式混亂。新的發佈在這個網站上。感謝您的反饋。 – mpease 2011-03-03 17:27:35

回答

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) 
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行作爲原始的海報要求。]