我有以下源代码。我上传了一个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))发布于 2021-03-18 07:03:44
您在这里有一个正确的想法,使用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语句中使用最后几行来执行wrap:
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))https://stackoverflow.com/questions/66682274
复制相似问题