使用Python

时间:2018-06-22 13:49:42

标签: python text

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

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)并将整个数据保存在一个新文件中? 预先感谢

4 个答案:

答案 0 :(得分:0)

对于文件的每一行,

    vals = line.split(' ')
    my_val = float(vals[4])/900
    output  = open('filename', 'wb')
    output.write(my_val +'\n')

答案 1 :(得分:0)

您可以使用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')

答案 2 :(得分:0)

使用简单的迭代。

res = []
with open(filename, "r") as infile:
    for line in infile:                        # Iterate each line 
        val = line.split()                     # Split line by space
        res.append( str(float(val[-1])/900) )  # Use negative index to get last element and divide.

with open(filename, "w") as outfile:          #Open file to write
    for line in res:
        outfile.write(line+"\n")              #Write Data

答案 3 :(得分:0)

您可以尝试以下操作:

import numpy as np
#Suppose your text data name is "CH3CH2OH_g.txt"
file = np.loadtxt('CH3CH2OH_g.txt')

z=  (file[:, -1]/900)
np.savetxt('LogCH3CH2OH.txt', file, fmt='%.2f')