Save results to csv file with Python
1 2 3 4 5 6 7 8 9 10 11 12 13 | import csv with open('test.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[1]] += 1 for row in data: if counter[row[1]] >= 4: writer = csv.writer(open("test1.csv","wb")) writer.writerows(row) |
我得到了奇怪的输出!这个代码有什么问题?
我知道问题是关于您的"csv"包实现,但对于您的信息,有一些更简单的选项,例如numpy。
1 2 | import numpy as np np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',') |
(为了子孙后代,这个答案在6年后公布。)
在另一个类似于您所问的情况下,假设您有两个这样的列:
1 2 | names = ['Player Name', 'Foo', 'Bar'] scores = ['Score', 250, 500] |
你可以这样保存它:
1 | np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s') |
1 2 3 | Player Name,Score Foo,250 Bar,500 |
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[0]] += 1 writer = csv.writer(open("/path/to/my/csv/file", 'w')) for row in data: if counter[row[0]] >= 4: writer.writerow(row) |
您可以关闭不是csv.writer对象的文件,它应该是:
1 2 3 4 5 | f = open(fileName,"wb") writer = csv.writer(f) String[] entries ="first*second*third".split("*"); writer.writerows(entries) f.close() |
一个简单的例子是:
1 2 3 4 | writer = csv.writer(open("filename.csv","wb")) String[] entries ="first#second#third".split("#"); writer.writerows(entries) writer.close() |
我就是这样做的
1 2 3 4 5 6 7 8 9 10 11 | import csv file = open('???.csv', 'r') read = csv.reader(file) for column in read: file = open('???.csv', 'r') read = csv.reader(file) file.close() file = open('????.csv', 'a', newline='') write = csv.writer(file, delimiter =",") write.writerow((, )) file.close() |
这将提供准确的输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import csv import collections with open('file.csv', 'rb') as f: data = list(csv.reader(f)) counter = collections.defaultdict(int) for row in data: counter[row[0]] += 1 writer = csv.writer(open("file1.csv", 'w')) for row in data: if counter[row[0]] >= 1: writer.writerow(row) |