所以我需要有关如何在Python中生成和格式化.txt输出文件的提示。
现在,我有一个接受输入和输出计算的脚本。 我想要一个总结所有计算和结果的.txt文件。
我的问题不是如何创建文件。我需要有关如何正确编写代码的提示,以便.txt文件看起来正常和整洁。
# input
a = 1
b = 2
c = 3
# output
d = 4
e = 5
f = 6
path = 'C:\Python27'
name = 'Test'
foo = open ( '%s/%s.txt' % (path , name), 'w')
foo.write('\t\t%s\n\n\n' %name)
foo.write('\t\t--------------Input-----------------\n\n')
foo.write('a = %r \"Input \'a\'" \nb = %r \"Input \'b\'\" \nc = %r \"Input \'c\'\" \n\n\n ' % (a, b, c))
foo.write('\t\t--------------Output-----------------\n\n')
foo.write('d = %r \"Output \'d\'\" \ne = %r \"Output \'e\'\" \nf = %r \"Output \'f\'\" \n\n\n ' % (d, e, f))
foo.close()
这会产生这样的结果:
Test
--------------Input-----------------
a = 1 "Input 'a'"
b = 2 "Input 'b'"
c = 3 "Input 'c'"
--------------Output-----------------
d = 4 "Output 'd'"
e = 5 "Output 'e'"
f = 6 "Output 'f'"
必须有一种更简单的方法吗?
我有40个参数加上要写的文字......
答案 0 :(得分:1)
inputs = {'a': 1, 'b': 2, 'c', 3} #dictionaries are better for what you need to do
outputs = {'d':4, 'e':5, 'f': 6}
foo = open('test.txt', 'wb')
foo.write('\t\t test \n\n\n')
foo.write('\t\t--------------Input-----------------\n\n')
for input, value in inputs.items(): #items will generate a list of tuples
foo.write('{0} = {1}'.format(input, value)) #or any other formatting you'd like
foo.write('\n')
然后为输出做同样的事。