繁体   English   中英

如何将字符串列表写入文件,添加换行符?

[英]How can I write list of strings to file, adding newlines?

考虑:

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

我想在每个“c + n”之后添加一个换行符。

改变

data.write(c + n)

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

正确放置的data.write('\n')将处理该问题。 只需为要标点的循环适当缩进即可。

正如其他答案已经指出的那样,您可以通过将 '\n' 附加到c+n或使用格式字符串“%s%s\n”来做到这一点。

作为一个有趣的问题,我认为使用列表推导而不是两个嵌套循环会更加Pythonic

data.write("\n".join("%s%s"%(c, n) for c in s_chars for n in nums))

改变

data.write(c + n)

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

使用writelinesproduct将更多工作推到 C 层:

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

这产生了与嵌套循环相同的效果,但使用 C 中实现的内置函数(无论如何在 CPython 参考解释器中)这样做,从而消除了图片中的字节码执行开销; 这可以显着提高性能,特别是对于较大的输入,并且与其他涉及'\n'.join的解决方案不同。将整个输出连接到单个字符串中以执行单个write调用,它在写入时进行迭代,因此峰值内存使用量保持不变要求您在单个字符串中一次实现内存中的整个输出。

Python 的print是标准的“用换行符打印”函数。

因此,如果您使用 Python 2.x,您可以直接执行以下操作:

print  >> data, c+n

如果您使用 Python 3.x:

print(c+n, file=data)

这个对我有用

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

利用

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

或者

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

取决于你想要什么。

我认为您可以使用join来简化内部循环:

data = open("list.txt", "w")
for c in s_chars:
    data.write("%s%s\n" % (c, c.join(nums)))
data.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM