Python 2.7 如何在python中读取数据txt文件并在特定条件下更改值
我需要更改输出数据文件中具有特定条件的值。输出文件的示例如下所示:Python 2.7 如何在python中读取数据txt文件并在特定条件下更改值,python-2.7,Python 2.7,我需要更改输出数据文件中具有特定条件的值。输出文件的示例如下所示: #comments 1 0 0.002799 296.404062 2.474652 1.769134 2 0 0.002799 293.540280 2.474652 1.769134 3 0 0.002799 296.404062 0.821247 4.107403 4 0 0.002799 290.676497 2.474652 1.769134 5 0 0.002799 287.812715 2.474652 1.769
#comments
1 0 0.002799 296.404062 2.474652 1.769134
2 0 0.002799 293.540280 2.474652 1.769134
3 0 0.002799 296.404062 0.821247 4.107403
4 0 0.002799 290.676497 2.474652 1.769134
5 0 0.002799 287.812715 2.474652 1.769134
6 0 0.002799 296.404062 2.474652 1.769134
如果行中的最后一个值小于8,我需要将第二个值(默认为零)更改为1,否则保留为零。有人能帮我吗 根据您的方法,a提出了以下代码:
with open(infile.chkpt) as fin,open('outfile.txt','w') as fout:
for line in fin:
#use line.split('\t'3) if the name of the field can contain spaces
float,float,rest = line.split('\t'3)
#do something to change start and end here.
#Note that `start` and `end` are strings, but they can easily be changed
#using `int` or `float` builtins.
fout.write('\t'.join((name,start,end,rest)))
with open('data.txt') as fin, open('outfile.txt','w') as fout:
for line in fin:
if line.startswith("#"):
fout.write(line)
continue
fields = line.split()
fields[1] = "0" if float(fields[-1]) < 8 else "1"
fout.write(" ".join(fields) + "\n")
以open('data.txt')作为fin,open('outfile.txt','w')作为fout:
对于fin中的行:
如果line.startswith(“#”):
四、写(行)
持续
fields=line.split()
如果浮点(字段[-1])小于8,则字段[1]=“0”,否则为“1”
fout.write(“.join(fields)+”\n”)
- 如果
以行
开头,则继续#
- 然后它将该行转换为单个
字段的数组
- 如果最后一个字段小于8(在转换为
后),则第二个字段设置为“0”-,如果不是,则设置为“1”float
- 最后,它连接字段并将它们写入输出文件