问题描述
我有以下源代码。 我上传了一个 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))