# create list [1 ... 999] ... we will pretend this is your input data
data = range(1, 1000)
def write_data(filename, data, per_line=16):
with open(filename, "w+") as f:
# get number of lines
iterations = (len(data) / per_line) + 1
for i in range(0, iterations):
# 0 on first iteration, 16 on second etc.
start_index = i * per_line
# 16 on first iteration, 32 on second etc.
end_index = (i + 1) * per_line
# iterate over data 16 elements at a time, from start_index to end_index
line = [str(i) for i in data[start_index:end_index]]
# write to file as comma seperated values
f.write(", ".join(line) + " \n")
# call our function, we can specify a third argument if we wish to change amount per line
write_data("output.txt", data)
您只需每16个元素添加一个字符
'\n'
(新行字符)。 您可以通过迭代您的数据轻松地做到这一点。你知道吗可以使用Python的列表切片。见here if you are unfamiliar。你基本上需要一个16个元素宽的“滑动窗口”。你知道吗
一种解决方案:
相关问题 更多 >
编程相关推荐