Skip to main content
 首页 » 编程设计

python之计算 CSV 中有多少列

2025年05月04日18lvdongjie

我只是把玩类和方法作为一种学习练习。

我努力创建的方法是一种计算 CSV 中有多少列的新方法。

我如何计算 CSV 中有多少列?

到目前为止,我的类(class),(很高兴您能指出其中的错误)。

import csv 
 
class CSV: 
 
 
    def __init__(self, file=None): 
        self.file = file 
 
    def read_file(self): 
        data = [] 
        file_read = csv.reader(self.file) 
        for row in file_read: 
            data.append(row) 
        return data 
 
    def get_row_count(self): 
        return len(self.read_file()) 
 
    def get_data(self, rows=1): 
        data = self.read_file() 
 
        return data[:rows]  

请您参考如下方法:

如果您确定所有行的列数都相同,那么您可以简单地读取第一行并获取其长度:

self.file_read = csv.reader(self.file) 
self.columns = len(self.file_read.next()) 

请注意 .next() 消耗一行。 (如果使用 Python 3,您将执行 len(next(self.file_read))。