Python:用三列整数编写一个数据文件

时间:2013-05-02 05:12:02

标签: python

我正在使用的代码是:

fout = open('expenses.0.col', 'w')  
for line in lines:
  words = line.split()
  amount = amountPaid(words)
  num = nameMonth(words)
  day = numberDay(words)
  line1 = amount, num, day
  fout.write(line1)
fout.close()

有一个文件,你无法看到行中的行正在从中运行就好了。行内有100行。在编写最后一段代码时,目标是获得100行三列,其中包含值:amount,num和day。所有这三个值都是整数。

我见过类似的问题,例如[python]Writing a data file using numbers 1-10,我得到了与该示例相同的错误。我的问题是将dataFile.write(“%s \ n”%line)应用于我的案例,每行有三个数字。应该是快速的1行代码修复。

3 个答案:

答案 0 :(得分:0)

使用print语句/函数而不是write方法。

答案 1 :(得分:0)

在你的例子中,line1是一个数组元组(我假设函数amountPaid(), nameMonth(), numberDay()都返回一个整数或浮点数。)

你可以做以下两件事之一:

  • 让这些函数将数字作为字符串值返回
  • 或将返回值转换为字符串,即:amount = str(amountPaid(words))

一旦这些值成为字符串,您就可以这样做:

line1 = amount, num, day, '\n'
fout.write(''.join(line1))

希望有所帮助!

答案 2 :(得分:0)

line1 = amount, num, day
fout.write("{}\n".format("".join(str(x) for x in line1)))
相关问题