用Python编写文件

时间:2013-12-08 06:47:59

标签: python

我想覆盖文件名student_information.txt。我试过了:

attribute_name = ["student_id", "name", "department", "sex", "age", "nationality",                      "grade"]
attribute_type = ["INT", "CHAR(20)", "CHAR(50)", "CHAR(1)", "INT", "CHAR(3)", "FLOAT"]
student_list = [("student_id", "name", "department", "sex", "age", "nationality", "grade"), ("student_id", "name", "department", "sex", "age", "nationality", "grade")]
f = open("student_information.txt", "w")
f.write('\n'.join('%s %s %s %s %s %s %s' % x for x in attribute_name))
f.write('\n'.join('%s %s %s %s %s %s %s' % x for x in attribute_type))
for i in range(len(student_list)):
    f.write('\n'.join('%s %s %s %s %s %s %s' % x for x in student_list[i]))
f.close()

它提出错误说:

TypeError: not enough arguments for format string.

任何人都有任何想法为什么它不起作用? 感谢。

2 个答案:

答案 0 :(得分:3)

替换此(以及其他类似事件):

'%s %s %s %s %s %s %s' % x for x in attribute_name)

'%s %s %s %s %s %s %s' % tuple(x for x in attribute_name))

<强>编辑:
实际上你的下面的代码看起来很奇怪:

f.write('\n'.join('%s %s %s %s %s %s %s' % x for x in attribute_name))

join的参数已经是单个字符串,结果实际上是在每个字符之间插入换行符

>>> '\n'.join('1234')
'1\n2\n3\n4'

我想你只需要这个:

f.write('%s %s %s %s %s %s %s\n' % tuple(x for x in attribute_name)) 

再次编辑:
@ John1024的答案看起来是正确的,你只需要直接使用列表名称:

f.write('%s %s %s %s %s %s %s\n' % tuple(attribute_name)) # convert list to tuple

再次编辑:
对不起,但我想我应该更明确地解释原因 在Python中使用格式化字符串时,参数列表应该传递给元组:

'parameters: %s %s' %('param0', 'param1')

虽然只有一个参数,但两种方式都可以写:

'parameters: %s' %('param0')
'parameters: %s' %'param0'

让我们看看这个:

>>> lst = [1, 2]
>>> '%d %d' % lst # this shall fail since the parameter list type doesn't match
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not list
>>> '%d %d' %tuple(lst) # while this shall work
'1 2'
>>> tuple(lst) # this generates a tuple from lst
(1, 2)

答案 1 :(得分:1)

如果您正在尝试创建学生信息表,我猜测您希望对代码进行多项更改:

attribute_name = ("student_id", "name", "department", "sex", "age", "nationality",                      "grade")
attribute_type = ("INT", "CHAR(20)", "CHAR(50)", "CHAR(1)", "INT", "CHAR(3)", "FLOAT")
student_list = [("student_id", "name", "department", "sex", "age", "nationality", "grade"), ("student_id", "name", "department", "sex", "age", "nationality", "grade")]
f = open("student_information.txt", "w")
f.write('%s %s %s %s %s %s %s\n' % attribute_name)
f.write('%s %s %s %s %s %s %s\n' % attribute_type)
for i in range(len(student_list)):
    f.write('%s %s %s %s %s %s %s\n' % student_list[i])
f.close()

这会产生一个类似于:

的文件
student_id name department sex age nationality grade
INT CHAR(20) CHAR(50) CHAR(1) INT CHAR(3) FLOAT
student_id name department sex age nationality grade
student_id name department sex age nationality grade

(如果您希望项目顺利排列,则应指定%s格式项目的宽度。)