猿问

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

我有一个文本文件,如下所示:


1  1  2  1  1e8

2  1  2  3  1e5

3  2  3  2  2000

4  2  5  6  1000

5  2  4  3  1e4

6  3  6  4  5000

7  3  5  2  2000

8  3  2  3  5000

9  3  4  5  1e9

10 3  2  3  1e6

我的问题是,如何更改一列(例如将所有数据从最后一列除以900)并将整个数据保存在一个新文件中?提前致谢


侃侃无极
浏览 284回答 3
3回答

千万里不及你

您可以使用numpy库。下面的代码应该做到这一点。import numpy as np# assume the data is in.txt filedat = np.loadtxt('in.txt')# -1 means the last columndat[:, -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 precisionnp.savetxt('out.txt', dat, fmt='%.2f')

达令说

对于文件的每一行,    vals = line.split(' ')    my_val = float(vals[4])/900    output  = open('filename', 'wb')    output.write(my_val +'\n')
随时随地看视频慕课网APP

相关分类

Python
我要回答