我想打開可變數量的 csv 檔案,然后我想遍歷打開的 csv 檔案并將每個檔案的 1 行一次上傳到我的 sql 資料庫。例如,遍歷每個檔案,將每個檔案的第一行上傳到資料庫,然后再次遍歷每個檔案,將每個檔案的第二行上傳到資料庫。但是,我堅持要準備好將 csv 檔案上傳到單個物件中。錯誤發生在 'csv_data[i] = csv.reader...' 每個檔案都用于不同的表,因此我無法附加它們。
import csv
import sys
i = 0
for argv in sys.argv[1:]:
csv_file = open(argv, newline='', encoding='utf-8-sig')
csv_data[i] = csv.reader(csv_file, dialect='excel', delimiter=',', quotechar='|')
csv_file.close()
i = 1
在這段代碼之后,我需要一些東西來回圈每個上傳某個行號的檔案。
uj5u.com熱心網友回復:
zip 將檔案放在一起,遍歷它們:
file_handles = [open(file, newline='', encoding='utf-8-sig') for file in argv[1:]]
readers = (csv.reader(file, dialect='excel', delimiter=',', quotechar='|') for file in file_handles)
# zip here
for line_group in zip(*readers):
# line_group is a tuple of line i of each file
# don't forget to close your files
for file_handle in file_handles:
try:
file_handle.close()
except:
print("Issue closing one of the files")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337211.html
