为了账号安全,请及时绑定邮箱和手机立即绑定

使用Python从文本文件更改特定的列值

使用Python从文本文件更改特定的列值

侃侃无极 2021-04-07 14:10:15
我有一个文本文件,如下所示:1  1  2  1  1e82  1  2  3  1e53  2  3  2  20004  2  5  6  10005  2  4  3  1e46  3  6  4  50007  3  5  2  20008  3  2  3  50009  3  4  5  1e910 3  2  3  1e6我的问题是,如何更改一列(例如将所有数据从最后一列除以900)并将整个数据保存在一个新文件中?提前致谢
查看完整描述

3 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

您可以使用numpy库。下面的代码应该做到这一点。


import numpy as np


# assume the data is in.txt file

dat = np.loadtxt('in.txt')


# -1 means the last column

dat[:, -1] = dat[:, -1]/900


# write the result to the out.txt file

# fmt is the format while writing to the file

# %.2f means that it will save it to the 2 digits precision

np.savetxt('out.txt', dat, fmt='%.2f')


查看完整回答
反对 回复 2021-04-13
?
达令说

TA贡献1821条经验 获得超6个赞

对于文件的每一行,


    vals = line.split(' ')

    my_val = float(vals[4])/900

    output  = open('filename', 'wb')

    output.write(my_val +'\n')


查看完整回答
反对 回复 2021-04-13
  • 3 回答
  • 0 关注
  • 283 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号