Python:csv-在列中查找值

Python:csv-在列中查找值,python,csv,Python,Csv,假设我有一个csv文件,如下所示: (a,3,,,,) (b,,,,,) (c,2,,,,) (d,,,,,) (e,,,,,) (f,1,,,,) (g,,,,,) 我试图找出哪个字母表(即a、b、c、d、e、f、g)在第1列中有一个值(假设这里是第1列)。 我写的代码如下: set3 = set([n[column] for n in new_marks]) if set3 != '': print print '{0} is not empty'.format

假设我有一个csv文件,如下所示:

(a,3,,,,)
(b,,,,,)
(c,2,,,,)
(d,,,,,)
(e,,,,,)
(f,1,,,,)
(g,,,,,)
我试图找出哪个字母表(即a、b、c、d、e、f、g)在第1列中有一个值(假设这里是第1列)。
我写的代码如下:

set3 = set([n[column] for n in new_marks])

if set3 != '':

      print
      print '{0} is not empty'.format(list(set3))
此代码仅打印第1列中的值,不打印字母

有人能帮我解决这个问题吗

谢谢

修改第一行:

d = dict((n[0], n[column]) for n in new_marks)
if d:
    print
    print '{0} is not empty'.format(d.keys())
set3 = set([n[0] for n in new_marks if n[column] is not None])
修改第一行:

set3 = set([n[0] for n in new_marks if n[column] is not None])

没有
csv
解决方案:

with open('data.txt') as f:
    for x in f:
        x=x.strip().strip('()')
        spl=x.split(',')
        if spl[0] in ('a','b','c','d','e','f','g') and spl[1]!='':  #replace spl[1] with
                          # any other column if you want to find value in some other column
            print ("{0} is not empty".format(spl[0]))
输出:

a is not empty
c is not empty
f is not empty

没有
csv
解决方案:

with open('data.txt') as f:
    for x in f:
        x=x.strip().strip('()')
        spl=x.split(',')
        if spl[0] in ('a','b','c','d','e','f','g') and spl[1]!='':  #replace spl[1] with
                          # any other column if you want to find value in some other column
            print ("{0} is not empty".format(spl[0]))
输出:

a is not empty
c is not empty
f is not empty

这段代码与我从你的问题中理解的差不多

我不确定您定义的“值”是什么,所以这里它只是任何一行有超过1列。但这段代码很容易修改

#holds the rows from the file
rows = []
#opens and reads each row of the file (CSVFILE = full file location)
with open(CSVFILE, "r") as CSV_read:
    next(CSV_read) # removes headers/colum names (if you dont have any - remove this line)
    for line in CSV_read:
        #cleans and splits the line into colums
        vals = line.strip("\r\n").strip("\n").split(",")
        #adds the line to the list of rows
        rows.append(vals)

#holds the alphabet (first colum value) of each row that has more values/cells
have_value = []
#goes over each row in the rows
for row in rows:
    #if there are any values after the initial 'alphabet'
    if len(row) > 1:
        # add to the list of things with values.
        have_value.append(row[0])

这段代码与我从你的问题中理解的差不多

我不确定您定义的“值”是什么,所以这里它只是任何一行有超过1列。但这段代码很容易修改

#holds the rows from the file
rows = []
#opens and reads each row of the file (CSVFILE = full file location)
with open(CSVFILE, "r") as CSV_read:
    next(CSV_read) # removes headers/colum names (if you dont have any - remove this line)
    for line in CSV_read:
        #cleans and splits the line into colums
        vals = line.strip("\r\n").strip("\n").split(",")
        #adds the line to the list of rows
        rows.append(vals)

#holds the alphabet (first colum value) of each row that has more values/cells
have_value = []
#goes over each row in the rows
for row in rows:
    #if there are any values after the initial 'alphabet'
    if len(row) > 1:
        # add to the list of things with values.
        have_value.append(row[0])
这个怎么样

s = """a,3,,,,
b,,,,,
c,2,,,,
d,,,,,
e,,,,,
f,1,,,,
g,,,,,"""
buf = StringIO(s)
d = {}
for row in csv.reader(buf,delimiter=','):
  d[row[0]] = row[1:]

looking_for = 2

for alpha,items in d.iteritems():
   try:
       if items[looking_for-1] == '1':
           print 'Letter %s has value in column %s' % (alpha,looking_for)
   except IndexError:
       print "List doesn't contain %s columns!" % looking_for
这个怎么样

s = """a,3,,,,
b,,,,,
c,2,,,,
d,,,,,
e,,,,,
f,1,,,,
g,,,,,"""
buf = StringIO(s)
d = {}
for row in csv.reader(buf,delimiter=','):
  d[row[0]] = row[1:]

looking_for = 2

for alpha,items in d.iteritems():
   try:
       if items[looking_for-1] == '1':
           print 'Letter %s has value in column %s' % (alpha,looking_for)
   except IndexError:
       print "List doesn't contain %s columns!" % looking_for

我会做类似的事情:

import csv

def strip_bits(obj):
    for el in obj:
        yield el[1:-2]

with open('/home/jon/testfile.csv') as fin:
    tempin = strip_bits(fin)
    csvin = csv.reader(tempin)
    for row in csvin:
        if any(row[1:]):
            print row[0] # or do whatever

我会做类似的事情:

import csv

def strip_bits(obj):
    for el in obj:
        yield el[1:-2]

with open('/home/jon/testfile.csv') as fin:
    tempin = strip_bits(fin)
    csvin = csv.reader(tempin)
    for row in csvin:
        if any(row[1:]):
            print row[0] # or do whatever

CSV只是一个纯逗号分隔的文本文件,不是吗

with open("/path/to/myfile.csv") as f:
    for line in f:
        line_chars = line.strip()[1:-1].split(",")
        k, v= line_chars[0], "".join(line_chars[1:])
        if v: print k, v

CSV只是一个纯逗号分隔的文本文件,不是吗

with open("/path/to/myfile.csv") as f:
    for line in f:
        line_chars = line.strip()[1:-1].split(",")
        k, v= line_chars[0], "".join(line_chars[1:])
        if v: print k, v

set3
作为一个集合,永远不会等于空字符串。
set3
作为一个集合,永远不会等于空字符串。CSV文件可能在引号中包含逗号分隔符,这使其成为列内容的一部分,而不是分隔符。。。所以,虽然(有时)纯粹在一根绳子上劈开很可爱,但你不能…@Jon,对,我只是忘了。谢谢你指出这一点。如果在Keww的例子中只有整数(如他的示例所示),那么我的代码仍然可以工作;-)CSV文件可能在引号中包含逗号分隔符,这使其成为列内容的一部分,而不是分隔符。。。所以,虽然(有时)纯粹在一根绳子上劈开很可爱,但你不能…@Jon,对,我只是忘了。谢谢你指出这一点。如果在Keww的例子中只有整数(如他的示例所示),那么我的代码仍然可以工作;-)