Python 读、写 txt

save

# save msg
if opt['train']['msg_save']:
    msg_save = message.detach().cpu().numpy().astype(np.int)
    str_msg = ''.join(str(i) for i in msg_save)
    msg_save_path = log_folder + '/' + 'message.txt'
    with open(msg_save_path, "a+") as f:
        f.write(str_msg + '\n')

read

# read msg
if opt['train']['msg_read']:
    msgg = []
    with open(opt['path']['msg_read_path'], "r") as f:
        for line in f.readlines():
            line = line.strip('\n').strip('[').strip(']').split(' ')
            msg = []
            for i in line:
                msg.append(eval(i))
            msgg.append(msg)
message = torch.tensor(msgg).to(device).type(torch.float32)

指定读写模式
在这里插入图片描述

或者使用numpy, 可以指定保存数据的长度、位数

np.savetxt('array.txt', data, fmt='%i %1.4f %1.4f')

np.savetxt('array.txt', data, fmt=' '.join(['%i'] + ['%1.4f']*N))

猜你喜欢

转载自blog.csdn.net/mr1217704159/article/details/122522694
今日推荐