jython max()'int'对象不可迭代

时间:2018-11-05 14:20:06

标签: python jython

我正在寻求帮助。 我设法使用以下代码将row_id添加到我的文件中,并且工作正常。

  - replace:
      path: server.xml
      regexp: "^<!--{{ mark_2 }}-->"
      replace: "<{{ mark_2 }}>"
  - replace:
      path: server.xml
      regexp: "^<{{ mark_1 }}>"
      replace: "<!--{{ mark_1 }}-->"

结果:

  • 00000-标头
  • 00001-数据
  • 00002-数据
  • ....-数据
  • 00037-数据最后一行

问题是我需要将nr条记录放在标题行中(在本例中为00037)

当我使用

infile = open(inputfile, 'r')
outfile = open(outputfile, 'w')

for i, line in enumerate(infile): 
#write header
    row_sec = ("00000" + str(i))[-5:]
    row_nr = max(row_sec)
    outfile.write(row_sec + "Company" + column[0] + column[1] + row_nr + "\n")
outfile.close()
infile.close()

records = max(i) 

我得到错误 TypeError:“ int”对象不可迭代

我阅读并理解了此错误,但仍然无法弄清楚如何消除它。有一种聪明简单的方法来修复我的代码吗?

1 个答案:

答案 0 :(得分:0)

您可以延迟编写并从循环中获取变量:

buffer = []
for i, line in enumerate(infile): 
    # create line content
    buffer.append('%5d' % i + " Company " + line + "\n")
# i is still set to the last value
# write header
outfile.write('%5d' % i + " Elements\n")
for line in buffer:
    outfield.write(line)

这将写类似

00037 Elements
00000 Company ACME
00001 Company EMCA
...
00037 Company MECA

请注意,如果您需要设置第一个索引,则enumerate将使用可选参数start


如果文件大于可用内存,则可以读取两次而不是缓冲:

# read once to get number of entries
with open(inputfile, 'r') as infile:
    companies = sum(1 for line in infile)

infile = open(inputfile, 'r')
outfile = open(outputfile, 'w')

# write header
outfile.write('%5d' % companies + " Elements\n")
for i, line in enumerate(infile):
    row_sec = ("00000" + str(i))[-5:]