【发布时间】:2010-09-20 22:50:25
【问题描述】:
我有一些值要写入文本文件,每个值都必须位于每行的特定列。
例如,假设我有values = [a, b, c, d],我想将它们写在一行中,以便将 a 写在该行的第 10 列,b 写在 25 日,c 写在 34 日,并且d 在第 48 列。
我将如何在 python 中执行此操作?
python 有类似column.insert(10, a) 的东西吗?这会让我的生活更轻松。
感谢您的帮助。
【问题讨论】:
我有一些值要写入文本文件,每个值都必须位于每行的特定列。
例如,假设我有values = [a, b, c, d],我想将它们写在一行中,以便将 a 写在该行的第 10 列,b 写在 25 日,c 写在 34 日,并且d 在第 48 列。
我将如何在 python 中执行此操作?
python 有类似column.insert(10, a) 的东西吗?这会让我的生活更轻松。
感谢您的帮助。
【问题讨论】:
在这种情况下,我认为您只需将填充函数与 python 的 string formatting syntax 一起使用。
"%10d%15d%9d%14d"%values 之类的东西会将 a、b、c、d 的最右边的数字放在您列出的列上。
如果你想把最左边的数字放在那里,那么你可以使用:"%<15d%<9d%<14d%d"%values,并在前面加上 10 个空格。
编辑:出于某种原因,我在使用上述语法时遇到了问题……所以我像这样使用了newstyle formatting syntax:
" "*9 + "{:<14}{:<9}{:<14}{}".format(*values)
这应该打印出来,values=[20,30,403,50]:
......... <-- from " "*9
20............ <-- {:<14}
30....... <-- {:<9}
403........... <-- {:<14}
50 <-- {}
----=----1----=----2----=----3----=----4----=----5 <-- guide
20 30 403 50 <-- Actual output, all together
【讨论】:
class ColumnWriter(object):
def __init__(self, columns):
columns = (-1, ) + tuple(columns)
widths = (c2 - c1 for c1, c2 in zip(columns, columns[1:]))
format_codes = ("{" + str(i) + ":>" + str(width) +"}"
for i, width in enumerate(widths))
self.format_string = ''.join(format_codes)
def get_row(self, values):
return self.format_string.format(*values)
cw = ColumnWriter((1, 20, 21))
print cw.get_row((1, 2, 3))
print cw.get_row((1, 'a', 'a'))
如果您需要列在行与行之间变化,那么您可以做一个衬里。
import itertools
for columns in itertools.combinations(range(10), 3):
print ColumnWriter(columns).get_row(('.','.','.'))
它在错误检查方面有所懈怠。它需要检查columns 是否已排序以及len(values) == len(columns)。
它的值比分配用于保存它的区域长,但我不知道该怎么做。目前,如果发生这种情况,它会覆盖上一列。示例:
print ColumnWriter((1, 2, 3)).get_row((1, 1, 'aa'))
如果您有要写入文件的可迭代行,您可以这样做
rows = [(1, 3, 4), ('a', 'b', 4), ['foo', 'ten', 'mongoose']]
format = ColumnWriter((20, 30, 50)).get_row
with open(filename, 'w') as fout:
fout.write("\n".join(format(row) for row in rows))
【讨论】:
您可以使用mmap 模块来memory-map 一个文件。
http://docs.python.org/library/mmap.html
使用mmap,您可以执行以下操作:
fh = file('your_file', 'wb')
map = mmap.mmap(fh.fileno(), <length of the file you want to create>)
map[10] = a
map[25] = b
不确定这是否是您正在寻找的,但它可能有效:)
看来我可能误解了这个问题。旧答案如下
也许您正在寻找 csv 模块?
http://docs.python.org/library/csv.html
import csv
fh = open('eggs.csv', 'wb')
spamWriter = csv.writer(fh, delimiter=' ')
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
【讨论】: