使用Python更改文本文件中的特定列值
我有一个文本文件,如下所示:使用Python更改文本文件中的特定列值,python,text,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)并将整个数据保存在新文件中? 提前感谢您的每一行文件 vals =
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
请把你的密码寄出去