How to write list of strings to file, adding newli

2019-02-06 11:24发布

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".

9条回答
姐就是有狂的资本
2楼-- · 2019-02-06 12:03

Change

data.write(c + n)

to

data.write("%s%s\n" % (c, n))
查看更多
冷血范
3楼-- · 2019-02-06 12:09

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

查看更多
做自己的国王
4楼-- · 2019-02-06 12:10

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()
查看更多
萌系小妹纸
5楼-- · 2019-02-06 12:13

This one works for me

with open(fname,'wb') as f:
    for row in var:
        f.write(repr(row)+'\n')
查看更多
Bombasti
6楼-- · 2019-02-06 12:15

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楼-- · 2019-02-06 12:16
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.

查看更多
登录 后发表回答