如果前 5 行存在,则仅读取 csv

问题描述

我有以下源代码。 我上传一个 csv 文件并写入 BigQuery 中的表。 如果csv中有5行,我需要包含只有那个csv文件可以保存在表中的代码。如果没有 5 行,则停止该过程。

代码

    with open('/tmp/{}'.format(input_file),"r") as csvfile:
        lines = len(list(csvfile))-1
        csvfile.seek(0)
        reader = csv.reader(csvfile)
        for i,row in enumerate(reader):
            # add header 
            if add_header:
              if (i == 0):
                  header_value = row[0:]
              
              lst_csvfile.append(header_value)
              add_header = False
            
            # add rows
            if (i > 0):
              # transform cpf
              new_row = [trata_cpf(row[0]),row[1],row[2]]
              lst_csvfile.append(new_row)
    # write gcs
    db_data.to_csv('/tmp/{}'.format(input_file),index=False)
    gcs_upload('{}'.format(input_file),'/tmp/{}'.format(input_file),gcs_bucket_temp)
    print('Encrypt File DONE: {}'.format(input_file))

解决方法

您在这里使用 lines = len(list(csvfile))-1 来确定文件中有多少非标题行(记录)是正确的。您可以添加一个简单的 if 语句来跳过循环或从方法返回:

with open('/tmp/{}'.format(input_file),"r") as csvfile:
    lines = len(csvfile.readlines()) - 1

    csvfile.seek(0)
    reader = csv.reader(csvfile)

    if lines < 5:
        return  # assuming you do not want the last 3 lines to execute

    for i,row in enumerate(reader):
        # rest of code

如果你需要最后几行在 else 语句中执行换行:

    lines = len(csvfile.readlines()) - 1

    csvfile.seek(0)
    reader = csv.reader(csvfile)

    if lines >= 5:
        for i,row in enumerate(reader):
            # rest of code

    # write gcs
    db_data.to_csv('/tmp/{}'.format(input_file),index=False)
    gcs_upload('{}'.format(input_file),'/tmp/{}'.format(input_file),gcs_bucket_temp)
    print('Encrypt File DONE: {}'.format(input_file))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...