Python 需要为elif条件结果写入文件下一列的内容吗?

Python 需要为elif条件结果写入文件下一列的内容吗?,python,Python,我正在从一个文件中读取并检查第二列中的数字。我已执行以下检查: 数字小于0.20 数字小于0.30 数字小于0.40 数字小于0.50 如果条件1为true,则将满足条件的值作为输出文件中的第一列写入 如果条件2为true,则将满足条件的写入同一输出文件中的第二列 如果条件3为真,则将满足条件的值作为colunm3写入同一输出文件 如果条件4为真,则将满足条件的值写入同一输出文件中的colunm4 这就是我到目前为止所做的: f = open('outfilename','r') d

我正在从一个文件中读取并检查第二列中的数字。我已执行以下检查:

  • 数字小于0.20
  • 数字小于0.30
  • 数字小于0.40
  • 数字小于0.50
如果条件1为true,则将满足条件的值作为输出文件中的第一列写入

如果条件2为true,则将满足条件的写入同一输出文件中的第二列

如果条件3为真,则将满足条件的值作为colunm3写入同一输出文件

如果条件4为真,则将满足条件的值写入同一输出文件中的colunm4

这就是我到目前为止所做的:

  f = open('outfilename','r')
  d = open('newfile','w')
  lines = f.readlines()
  for line in lines:
  job = line.split()
  if(float(job[2]) < 0.20):
     d.write(str(job[2]))
     d.write('\n')
  elif(float(job[2]) < 0.30):
     d.write(str(job[2]))
     d.write('\n')
  elif(float(job[2]) < 0.40):
     d.write(str(job[2]))
     d.write('\n')
  elif(float(job[2]) < 0.50):
     d.write(str(job[2]))
     d.write('\n')

  d.close()
  f.close()

有人能帮我找出我的代码出了什么问题吗?

我想你应该做如下事情:

f = open('outfilename','r')
d = open('newfile','w')
lines = f.readlines()
for line in lines:
job = float(line.split()[2])
if(job < 0.20):
   d.write(str(job) + "\t\t\t\n")
elif(job < 0.30):
   d.write("\t" + str(job) + "\t\t\n")
elif(job < 0.40):
   d.write("\t\t" + str(job) + "\t\n")
elif(job < 0.50):
   d.write("\t\t\t" + str(job) + "\n")

d.close()
f.close()

这是关于列处理的更明确一点-您可以通过设置
only\u one

f = open('outfilename','r')
d = open('newfile','w')
limits = [0.2, 0.3, 0.4, 0.5]

only_first = True

for line in f:
    columns = ['' for l in limits]
    job = float(line.split()[2])
    for i, limit in enumerate(limits):
        if job < limit:
            columns[i] = str(job)
            if only_first: break
    d.write('\t'.join(columns) + '\n')
f=open('outfilename','r')
d=打开('newfile','w')
极限=[0.2,0.3,0.4,0.5]
只有_first=True
对于f中的行:
列=[''表示限制中的l]
作业=浮动(line.split()[2])
对于i,枚举中的限制(限制):
如果作业<限制:
列[i]=str(作业)
要是你先休息就好了
d、 写入('\t'.join(列)+'\n')

您可以使用tempString并在每个
if
语句中添加列,最后将该tempString写入文件。@ansh01检查编辑的数字。您将需要执行类似的操作以获得所需的输出。为了便于阅读,我添加了一个额外的
\t
f = open('outfilename','r')
d = open('newfile','w')
lines = f.readlines()
for line in lines:
    job = float(line.split()[2])
    output = "
    output = output + str(job) +"\t" if job < .2 else output + "\t\t"
    output = output + str(job) +"\t" if job < .3 else output + "\t\t"
    output = output + str(job) +"\t" if job < .4 else output + "\t\t"
    output = output + str(job) +"\t" if job < .5 else output + "\t\t"
    d.write(output+"\n")
d.close()
f.close()
f = open('outfilename','r')
d = open('newfile','w')
limits = [0.2, 0.3, 0.4, 0.5]

only_first = True

for line in f:
    columns = ['' for l in limits]
    job = float(line.split()[2])
    for i, limit in enumerate(limits):
        if job < limit:
            columns[i] = str(job)
            if only_first: break
    d.write('\t'.join(columns) + '\n')