Python:编写包含三列整数的数据文件

Python:编写包含三列整数的数据文件,python,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() 有一个文件,您无法看到行中的行正在从中提取,

我使用的代码是:

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。这三个值都是整数


我看到过类似的问题,比如,我得到了与那个例子相同的错误。我的问题是应用dataFile.write(“%s\n”%line)到我的案例中,每行有三个数字。应该是一行快速的代码修复。

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

在您的示例中,
line1
是一个数字元组(我假设函数
amountPaid()、namemountmonth()、numberDay()
都返回整数或浮点)

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

  • 让这些函数以字符串值的形式返回数字
  • 或将返回值转换为字符串,即:
    amount=
    str(支付金额(文字))
一旦这些值是字符串,您可以简单地执行以下操作:

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

希望有帮助

里面的答案完全解释了这个问题。参数line1应为字符串。从三个变量创建一个字符串,它应该可以工作。
int(amountPaid(words))
没有转换为字符串。缺少新行。而
str.join
只能合并字符串,因此这三个变量不能是整数,需要在合并前转换为字符串。
line1 = amount, num, day
fout.write("{}\n".format("".join(str(x) for x in line1)))