我有按日期命名的 CSV 檔案串列,例如:
2020-01-01, 2020-01-02... 2020-01-31
我需要將它們批量匯入 SQLite 資料庫。我的腳本:
file_name = '2020-01-{}.csv'
test = pd.concat([pd.read_csv(file_name.format(i)) for i in range(1, 9)])
test.to_sql('test', conn, if_exists='append', index=False)
但我必須手動添加第一天:
file_name = '2020-01-0{}.csv', file_name = '2020-01-1{}.csv', file_name = '2020-01-2{}.csv'...
如何將所有檔案匯入資料庫,只需給出年份和月份,使其可重復使用(這樣如果我添加新的 CSV 檔案,代碼只匯入新檔案)?
uj5u.com熱心網友回復:
您可以按照以下步驟執行此程序
- 列出所有檔案
- 運行一個回圈并將它們添加到資料庫中
所以作業解決方案應該像
import pandas as pd
def read_csv_file(file_name) -> pd.DataFrame:
"""Read csv file and return a dataframe"""
df = pd.read_csv(file_name)
return df
def get_all_csv_files() -> list:
"""Get all csv files in the directory"""
import glob
files = glob.glob("*.csv")
return files # Output : ['2020-01-01.csv', ... '2020-01-31.csv']
for file in get_all_csv_files():
"""Loop through all CSV files and do something"""
df = read_csv_file(file)
print(df)
# Do something with the dataframe here like adding into the database
# To move them into another directory/folder Create a folder "Processed" in the same dir
import shutil
shutil.move(file, "Processed")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529246.html
上一篇:插入資料庫失敗
下一篇:排序順序和管道符號
