Python data saving file (.txt .pkl .csv format) (continuously updated)

(1) Save as .txt format

save data

import time

# fileName 获取当前时间种子
fileName = time.localtime() 
with open(
        rf"Z:\{fileName.tm_year, fileName.tm_mon, fileName.tm_mday, fileName.tm_hour, fileName.tm_min, fileName.tm_sec}.txt",
        'w'
) as f:
    f.write(str(list))
    f.close()
  • The r and f before the path
  • r: Prevent characters in the path from being parsed as escape characters
  • f: parse fileName

Read data

 # file_path为读取的文件路径
 # r 只读
 with open(
 	filePath,
 	'r'
 ) as f:
     data_dict = f.read() 
     data_dict = eval(data_dict) # 将字符转换为dict格式
     f.close()

(2) Save as .pkl format

1. 适用于Pandas中,格式为DataFrame,Series类数据

File Saving (Pandas)

data.to_pickle(filePath)

File reading (Pandas)

data.read_pickle(filePath)

2. pickle模块保存

File saving (pickle module)

import pickle
# 'wb'中 w :写入 , b: 二进制
with open(filePath, 'wb') as f:
	pickle.dump(data, f)

File reading (pickle module)

import pickle
# 'wb'中 w :写入 , b: 二进制
with open(filePath, 'rb') as f:
	data = pickle.load(fp)

(3) Save as .csv format

1. 适用于Pandas中,格式为DataFrame,Series类数据

File Saving (Pandas)

# 若不需要columns 则 header=0
# 若不需要index 则 index=False
data.to_csv(filePath, index=False, header=False)

File reading (Pandas)

data.read_scv(filePath)

Guess you like

Origin blog.csdn.net/weixin_45725923/article/details/131639958