1 回答

TA貢獻2080條經驗 獲得超4個贊
import glob
import os
import pandas as pd
# inputs
path = input('Insert the directory path:')
group = input('Insert a group name: ')
# create a list of file paths
file_list = [file for file in glob.glob(path)]
# dict comprehension to create keys from file name and values from the csv files
dfs = {os.path.basename(os.path.normpath(filename)).split('.')[0]: pd.read_csv(filename) for filename in file_list}
# loop though the dataframes
for k,df in dfs.items():
# store the HDF5 file
store = pd.HDFStore('test.h5')
# append df to a group and assign the key with f-strings
store.append(f'{group}/{k}', df, format='table', data_columns=df.columns)
# close the file
store.close()
我為該組運行了上述代碼兩次,該組的結果如下:samplesample1
import h5py
# load file
f = h5py.File('test.h5', 'r')
print(f['sample'].keys())
print(f['sample1'].keys())
f.close()
<KeysViewHDF5 ['untitled', 'untitled1']>
<KeysViewHDF5 ['untitled2', 'untitled3']>
添加回答
舉報