1

我有以下格式的文本文件:

1,"20130219111529","90UP:34","0000","9999","356708","2"
"-2","20130219105824","0001:11","0000","","162_005",""

我想出于某种目的比较第 1 行和第 2 行(在本例中为 1 和 -2)。要删除所有引号并解析此文件,我有以下代码:

if os.path.exists(FileName):
    with open(FileName) as File:
        for row in csv.reader(File, delimiter= ',', skipinitialspace= True):
            print(row)

以下是输出:

['1', '20130219111529', '90UP:34', '0000', '9999', '356708', '2']
['-2', '20130219105824', '0001:11', '0000', '', '162_005', '']

我想遍历列。例如,遍历 '1' 然后 '-2' 等等。

我该怎么做呢?

4

4 回答 4

2

使用zip(). 它将两个可迭代对象转换为一个可迭代的元组,其中元素来自两个列表。

l1 = ['1', '20130219111529', '90UP:34', '0000', '9999', '356708', '2']
l2 = ['-2', '20130219105824', '0001:11', '0000', '', '162_005', '']

for elem1, elem2 in zip(l1, l2):
    print("elem1 is {0} and elem2 is {1}.".format(elem1, elem2)
于 2013-10-25T18:48:06.447 回答
1

只需打印行中的第一个元素:

for row in csv.reader(File, delimiter= ',', skipinitialspace= True):
            print(row[0])

编辑

rows = csv.reader(File, delimiter= ',', skipinitialspace= True)
print len(rows) # how many rows were read from the file
for row in rows:
    print(row[0])
于 2013-10-25T18:46:42.533 回答
1

如果(正如您在问题中所说,虽然我不确定您是否想要这个)您想要遍历columns,您可以执行以下操作:

if os.path.exists(file_name):
    with open(file_name) as csv_file:
        for columns in zip(*csv.reader(csv_file, delimiter=',', skipinitialspace=True)):
            print columns

这将输出以下内容:

('1', '-2')
('20130219111529', '20130219105824')
('90UP:34', '0001:11')
('0000', '0000')
('9999', '')
('356708', '162_005')
('2', '')
于 2013-10-25T18:58:35.800 回答
1

或许如下。

if os.path.exists(FileName):
    with open(FileName) as File:
        lastRow = []
        # loop over the lines in the file
        for row in csv.reader(File, delimiter= ',', skipinitialspace= True):
            # saves the first row, for comparison below
            if lastRow == []:
                lastRow = row
                continue

            # loop over the columns, if all rows have the same number
            for colNum in range(len(row)):
                # compare row[colNum] and lastRow[colNum] as you wish

            # save this row, to compare with the next row in the loop
            lastRow = row
于 2013-10-25T18:51:06.263 回答