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

百般思念 提交于 2019-12-18 13:05:23

问题


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.close()

I would like to add a newline after every "c + n".


回答1:


Change

data.write(c + n)

to

data.write("%s%s\n" % (c, n))



回答2:


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




回答3:


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))



回答4:


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)



回答5:


Change

data.write(c+n)

to

data.write(c+n+'\n')



回答6:


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.




回答7:


This one works for me

with open(fname,'wb') as f:
    for row in var:
        f.write(repr(row)+'\n')



回答8:


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.




回答9:


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()


来源:https://stackoverflow.com/questions/5429064/how-to-write-list-of-strings-to-file-adding-newlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!