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

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

    data =         


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

    Change

    data.write(c + n)
    

    to

    data.write("%s%s\n" % (c, n))
    
    0 讨论(0)
  • 2020-12-31 09:42

    A properly-placed data.write('\n') will handle that. Just indent it appropriately for the loop you want to punctuate.

    0 讨论(0)
  • 2020-12-31 09:42

    Python's print is the standard "print with newline" function.

    Therefore, you can directly do, if you use Python 2.x:

    print  >> data, c+n
    

    If you use Python 3.x:

    print(c+n, file=data)
    
    0 讨论(0)
  • 2020-12-31 09:45
    def generator():
         nums = ['09', '98', '87', '76', '65', '54', '43']
         s_chars = ['*', '&', '^', '%', '$', '#', '@',]
    
         data = open("list.txt", "w")
         for c in s_chars:
            for n in nums:
               data.write(c + n + "\n")
         data.close()
    

    OR

    def generator():
         nums = ['09', '98', '87', '76', '65', '54', '43']
         s_chars = ['*', '&', '^', '%', '$', '#', '@',]
    
         data = open("list.txt", "w")
         for c in s_chars:
            for n in nums:
               data.write(c + n)
            data.write("\n")
         data.close()
    

    depending on what you want.

    0 讨论(0)
  • 2020-12-31 09:51

    As other answers gave already pointed out, you can do it by appending a '\n' to c+n or by using the format string "%s%s\n".

    Just as a matter of interest, I think it would be more pythonic to use a list comprehension instead of two nested loops:

    data.write("\n".join("%s%s"%(c,n) for c in s_chars for n in nums))
    
    0 讨论(0)
  • 2020-12-31 09:53

    In the previously reply, I have made a wrong answer because I have misunderstood the requirements, please ignore it.

    I think you can use join to simplify the inner loop

    data = open("list.txt", "w")
    for c in s_chars:
        data.write("%s%s\n" % (c, c.join(nums)))
    data.close()
    
    0 讨论(0)
提交回复
热议问题