迭代python中的文本文件中的列

时间:2013-10-25 18:44:10

标签: python python-2.7

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

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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])

答案 2 :(得分: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

答案 3 :(得分:1)

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

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', '')