Python 2.7 python csv不打印副本
我们有许多csv文件,如下所示:Python 2.7 python csv不打印副本,python-2.7,csv,duplicates,Python 2.7,Csv,Duplicates,我们有许多csv文件,如下所示: Name,Type 1,Fuji 2,Fuji 3,Fuji 4,Fuji 5,Washington 6,Washington 7,Washington 8,Washington 9,Washington 我们希望打印出苹果的种类而不打印副本 Fuji:6 Washington:4 Gaza:1 或 以下是我们的尝试。尽管不知什么原因它似乎不起作用 # Python 2.7 import csv import glob import collecti
Name,Type
1,Fuji
2,Fuji
3,Fuji
4,Fuji
5,Washington
6,Washington
7,Washington
8,Washington
9,Washington
我们希望打印出苹果的种类而不打印副本
Fuji:6 Washington:4 Gaza:1
或
以下是我们的尝试。尽管不知什么原因它似乎不起作用
# Python 2.7
import csv
import glob
import collections
from collections import Counter
list = glob.glob('C:Apple*.csv')
for file in list:
infile = open(file, "rb")
reader = csv.reader(infile)
for column in reader:
Discipline = column[1]
print collections.Counter(Discipline)
infile.close()
我以前没有使用过csv模块,但这里有一个快速尝试,我认为您可能正在尝试实现
import csv
src = r'C:\apples_before.csv'
dst = r'C:\apples_after.csv'
apples = set([])
# Read file.
with open(src, 'r') as srcfile:
reader = csv.reader(srcfile, delimiter=',')
for index, row in enumerate(reader):
if index == 0:
continue
apples.add(row[1])
# Write file.
# @warning: Please note that I am making an assumption in terms of the number
# component. I am assuming it is a row number.
with open(dst, 'w') as dstfile:
writer = csv.writer(dstfile, delimiter=',')
for index, apple in enumerate(apples):
if index == 0:
writer.writerow(['Name', 'Type'])
writer.writerow([index + 1, apple])
您没有试图避免重复。你试过什么,到底出了什么问题?你对如何继续有什么想法吗?对不起,我发错了脚本。现在我已经更新了!谢谢。由于未知的原因,它似乎不起作用-您认为您可以提供一个关于错误的不太有用的描述吗?谢谢Yani提供的解决方案和详细的解释。我将上述输入更改为csv。您的脚本和上面的脚本没有生成任何输出文件。请问您有什么意见?谢谢我已经根据我认为你们正在努力实现的目标改变了我的答案。
import csv
src = r'C:\apples_before.csv'
dst = r'C:\apples_after.csv'
apples = set([])
# Read file.
with open(src, 'r') as srcfile:
reader = csv.reader(srcfile, delimiter=',')
for index, row in enumerate(reader):
if index == 0:
continue
apples.add(row[1])
# Write file.
# @warning: Please note that I am making an assumption in terms of the number
# component. I am assuming it is a row number.
with open(dst, 'w') as dstfile:
writer = csv.writer(dstfile, delimiter=',')
for index, apple in enumerate(apples):
if index == 0:
writer.writerow(['Name', 'Type'])
writer.writerow([index + 1, apple])