只有前 5 行存在时才读取 csv

Only read csv if the first 5 lines exist

我有以下源代码。 我上传一个 csv 文件并写入 BigQuery 中的 table。 如果 csv 中有 5 行,我需要包含只有该 csv 文件可以保存在 table 中的代码。如果没有 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 来确定文件中有多少 non-header 行(记录)是正确的想法。您可以添加一个简单的 if 语句来跳过循环或 return 来自方法:

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