python - 如何计算每一行的列数?

标签 python excel csv

每行都有不同的列数,但 A 列始终是文件名,其余列是该文件的字段。

有什么方法可以计算每行的列数吗?

import csv
file=('C:/)
with open('C:/Count.csv','w',encoding='cp949',newline='') as testfile:
    csv_writer=csv.writer(testfile)
    for line in file:
        lst=[len(line)]
        csv_writer.writerow(lst)

最佳答案

您可以选择用逗号分割或使用 csv 打开文件。

我推荐后者。以下是您可以执行此操作的方法:

file1 = ... # file to read
file2 = ... # file to write
with open(file1, 'r') as f1, open(file2, 'w', encoding='cp949', newline='') as f2:
    csv_reader = csv.reader(f1)
    csv_writer = csv.writer(f2)
    for row in csv_reader:
        csv_writer.writerow([len([x for x in row if x])]) # non-null counts only

同时打开两个文件,迭代要读取的文件,使用 len(row) 计算其列数,然后将其写出。

关于python - 如何计算每一行的列数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668212/

相关文章:

python - 在 Python 中使用 mdbtools 从 .mdb 文件中提取和排序数据

python - 在 csv 文件中使用 python 格式化从 twitter api 返回的数据?

python - 让 Python 在不同时间打印行

python - 没有名为 'dbus' 错误的模块

excel - 如何在 maatwebsite 3.1 的多个表单中使用 withEvents 应用样式?

c# - 如何在 C# 中将 double 值转换为 DateTime?

python - matplotlib 中带有标题、轴标签的确切图形大小

python - 存储前一行中两列 pandas 的差异

excel - 这个工作簿在 Excel 2018 中不起作用?

php - 如何在不重复 header 的情况下合并多个 CSV 文件(使用 PHP)?