How to write list of strings to file, adding newlines?

前端 未结 9 1380
借酒劲吻你
借酒劲吻你 2020-12-31 09:02
def generator():
    nums = [\'09\', \'98\', \'87\', \'76\', \'65\', \'54\', \'43\']
    s_chars = [\'*\', \'&\', \'^\', \'%\', \'$\', \'#\', \'@\',]

    data =         


        
相关标签:
9条回答
  • 2020-12-31 09:58

    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.

    0 讨论(0)
  • 2020-12-31 10:01

    Change

    data.write(c+n)
    

    to

    data.write(c+n+'\n')
    
    0 讨论(0)
  • 2020-12-31 10:02

    This one works for me

    with open(fname,'wb') as f:
        for row in var:
            f.write(repr(row)+'\n')
    
    0 讨论(0)
提交回复
热议问题