簡體   English   中英

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

[英]Change specific column values from a text file using 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)並將整個數據保存在新文件中? 提前致謝

對於文件的每一行,

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

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

使用簡單的迭代。

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

您可以嘗試以下操作:

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM