【问题标题】:Change specific column values from a text file using Python使用 Python 更改文本文件中的特定列值
【发布时间】:2018-06-22 13:49:42
【问题描述】:

我有一个文本文件如下:

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)并将整个数据保存在新文件中? 提前致谢

【问题讨论】:

  • 请发布您的代码

标签: python text


【解决方案1】:

您可以使用 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】:

    对于文件的每一行,

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

    【讨论】:

      【解决方案3】:

      使用简单的迭代。

      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
      

      【讨论】:

        【解决方案4】:

        您可以尝试以下方法:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-20
          • 2015-05-31
          • 1970-01-01
          相关资源
          最近更新 更多