def generator():
nums = [\'09\', \'98\', \'87\', \'76\', \'65\', \'54\', \'43\']
s_chars = [\'*\', \'&\', \'^\', \'%\', \'$\', \'#\', \'@\',]
data =
Pushing more work to the C layer with writelines
and product
:
from future_builtins import map # Only do this on Python 2; makes map generator function
import itertools
def generator():
nums = ['09', '98', '87', '76', '65', '54', '43']
s_chars = ['*', '&', '^', '%', '$', '#', '@',]
# Append newlines up front, to avoid doing the work len(nums) * len(s_chars) times
# product will realize list from generator internally and discard values when done
nums_newlined = (n + "\n" for s in nums)
with open("list.txt", "w") as data:
data.writelines(map(''.join, itertools.product(s_chars, nums_newlined)))
This produces the same effect as the nested loop, but does so with builtins implemented in C (in the CPython reference interpreter anyway), removing byte code execution overhead from the picture; this can dramatically improve performance, particularly for larger inputs, and unlike other solutions involving '\n'.join
of the whole output into a single string to perform a single write
call, it's iterating as it writes, so peak memory usage remains fixed instead of requiring you to realize the entire output in memory all at once in a single string.
Change
data.write(c+n)
to
data.write(c+n+'\n')
This one works for me
with open(fname,'wb') as f:
for row in var:
f.write(repr(row)+'\n')