Python中读写各种后缀名文件的包使用小卡片
json包的使用
1、加载.json文件,并将读取到的字符串转化为字典:
with open(json_path, 'r') as f_str:
train_dict = json.load(f_str)
2、将字典写入到.json文件中:
with open(path, 'w') as outf:
json.dump(pre_dict, outf)
注意:只有字符串才能写入文件,所以此处的dump()函数可以实现字典转字符串
pandas包的使用
1、读取.csv文件:
dataset = pd.read_csv(csv_path, sep='\t')
sep参数用来指定列与列之间的间隔方式,必须与写入.csv文件时一样
2、写入.csv文件:
dataframe = pd.DataFrame({
'video_id': video_ids,
'caption': captions,
'start': starts,
'end': ends,
'duration': durations,
})
# save to .csv file
dataframe.to_csv(path, index=None, sep='\t')
只有使用pd.DataFrame(data,columns=,index=)和pd.Series(data,index=)创建的数据结构才能使用pd来进行写入.csv文件操作