检查CSV每行中的列数 [英] Check for number of columns in each row of CSV

查看:111
本文介绍了检查CSV每行中的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Python代码:

I have the following Python code:

import os
import csv
import sys

g = open('Consolidated.csv', "wb")
for root, dirs, files in os.walk('D:\\XXX\\YYY\\S1'):
    for filename in files:
            pathname = os.path.join(root, filename)
            symbol = filename.rpartition('_')[-1].rpartition('.')[0]
            reader = csv.reader(open(pathname, 'rU'))
            writer = csv.writer(g, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

            for row in reader:
                row.insert(0, symbol.upper())
                if len(row[2]) == 3:
                    row[2] = '0'+row[2]
                writer.writerow(row)

基本思想是,我在S1中有几个CSV文件,我需要将这些文件合并到大型CSV文件中.这些文件以有趣的方式命名,这导致代码中的rpartition和行操作.

The basic idea is that I have a couple of CSV files in S1 that I need to merge to a large CSV. The files are named in a funny way, which leads to the rpartition and row manipulations in the code.

此代码可以正常工作,但是我的问题如下:如何检查CSV文件的EACH行中的列数?例如:如果输入的CSV文件采用以下格式,并且预期包含五列:1、2、3、4、5,则代码将显示"1","2","3","4","5"(在合并文件中用制表符分隔).现在,无论出于何种原因,让我们说一下CSV文件中的一行条目是:6,7,8.因此,它会突然停止,而不会填充所有列.在这种情况下,我希望代码忽略此行,而不会在合并中产生"6","7","8".

This code works fine, but my question is as follows: how does one check the number of columns in EACH row of the CSV file? An example: if an input CSV file is in the following format, expected to have five columns: 1,2,3,4,5, the code would display "1" "2" "3" "4" "5" (seperated by tabs) in the consolidated file. Now let's say for whatever reason one row entry in the CSV file is like: 6,7,8. So it stops abruptly without all the columns filled in. In this case, I want the code to ignore this line and not produce "6" "7" "8" into the consolidation.

有人可以提供有关如何执行此操作的代码吗?对于输入的CSV中的每一行,我想在操作它之前检查它是否为完整行.

Could someone kindly provide code on how to do so? For each row in the input CSVs I want to check if it is a full row before manipulating it.

任何帮助将不胜感激.

温暖的问候.

推荐答案

len(row)

将给出行中的列数.

你可以做

for row in reader:
    if not len(row)<desired_number_of_columns:
        # process the row here

例如,如果您的csv文件如下所示

For example, if your csv file looks like this

1,2,3,4,5
a,b,c,d,e
l1,l2
d,e,f,g,h

运行

import csv
reader = csv.reader(open("csvfile.csv","r"))
for row in reader:
    if not len(row)<5:
        print(" ".join(row))

将产生输出

1 2 3 4 5
a b c d e
d e f g h

忽略长度为2的行.

这篇关于检查CSV每行中的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆