我目前正在以“rb”模式讀取 csv 檔案并將檔案上傳到 s3 存盤桶。
with open(csv_file, 'rb') as DATA:
s3_put_response = requests.put(s3_presigned_url,data=DATA,headers=headers)
所有這些都作業正常,但現在我必須在進行 put 呼叫之前驗證 csv 檔案中的標題。
當我嘗試在下面運行時,出現錯誤。
with open(csv_file, 'rb') as DATA:
csvreader = csv.reader(file)
columns = next(csvreader)
// run-some-validations
s3_put_response = requests.put(s3_presigned_url,data=DATA,headers=headers)
這拋出
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
作為一種解決方法,我創建了一個新函式,它以“r”模式打開檔案并對 csv 標頭進行驗證,這可以正常作業。
def check_csv_headers():
with open(csv_file, 'r') as file:
csvreader = csv.reader(file)
columns = next(csvreader)
我不想兩次讀取同一個檔案。一次用于標頭驗證,一次用于上傳到 s3。如果我在“r”模式下上傳,上傳部分也不起作用。
有沒有辦法在“rb”模式下僅讀取一次檔案時實作這一點?我必須使用csv module而不是 pandas 庫來完成這項作業。
uj5u.com熱心網友回復:
做你想做的事是可能的,但效率不是很高。簡單地打開一個檔案并不是那么昂貴。CSV 閱讀器一次只能讀取一行,而不是整個檔案。
要做你想做的事,你必須:
- 將第一行讀取為位元組
- 將其解碼為字串(使用正確的編碼)
- 將其轉換為字串串列
csv.reader最后決議它- 尋找流的開始。
否則,您最終只會上傳沒有標題的資料:
with open(csv_file, 'rb') as DATA:
header=file.readline()
lines=[header.decode()]
csvreader = csv.reader(lines)
columns = next(csvreader)
// run-some-validations
DATA.seek(0)
s3_put_response = requests.put(s3_presigned_url,data=DATA,headers=headers)
以文本形式打開檔案不僅更簡單,它還允許您將驗證邏輯與上傳代碼分開。
為確保一次只讀取一行,您可以使用buffering=1
def check_csv_headers():
with open(csv_file, 'r', buffering=1) as file:
csvreader = csv.reader(file)
columns = next(csvreader)
// run-some-validations
with open(csv_data, 'rb') as DATA:
s3_put_response = requests.put(s3_presigned_url,data=DATA,headers=headers)
或者
def check_csv_headers():
with open(csv_file, 'r', buffering=1) as file:
csvreader = csv.reader(file)
columns = next(csvreader)
// run-some-validations
//If successful
return True
def upload_csv(filePath):
if check_csv_headers(filePath) :
with open(csv_data, 'rb') as DATA:
s3_put_response = requests.put(s3_presigned_url,data=DATA,headers=headers)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475884.html
