为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 output.txt 中打印输出并每行列出

如何在 output.txt 中打印输出并每行列出

素胚勾勒不出你 2023-03-30 10:22:14
我有一个代码可以打印 ascii_lowercase 的所有 6 个字符串组合。这是代码:from itertools import productfrom string import ascii_lowercasekeywords = [''.join(i) for i in product(ascii_lowercase, repeat = 2)]print(keywords)输出是这样的。['aa', 'ab', 'ac', 'ad',...'zx', 'zy', 'zz']像这样打印它占用了命令提示符中的所有空间。我怎样才能将它打印到一个 output.txt 文件,而不是每行列表 2 个字符串?例如,而不是['aa', 'ab', 'ac', 'ad',...'zx', 'zy', 'zz']我想在 output.txt 文件中这样输出aaabac...zyzz
查看完整描述

6 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

您将需要遍历列表并打印每个项目而不是打印列表本身


with open('output.txt', 'w') as f:

    for k in ''.join(i) for i in product(ascii_lowercase, repeat = 2):

        f.write('{}\n', k)


查看完整回答
反对 回复 2023-03-30
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

把事情简单化。如果您对该输出要做的只是将其逐行写入文件,那么您甚至不需要首先生成列表:


from itertools import product

from string import ascii_lowercase


with open('output.txt', 'w') as f:

    for i in product(ascii_lowercase, repeat=2):

        f.write(''.join(i) + '\n')


查看完整回答
反对 回复 2023-03-30
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

以下是如何使用上下文管理器:


from itertools import product

from string import ascii_lowercase


with open('output.txt','w') as f:

    for i in product(ascii_lowercase, 2)

        f.write(''.join(i)+'\n')


查看完整回答
反对 回复 2023-03-30
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

from itertools import product

from string import ascii_lowercase

keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 2)]


for i in range(0,len(keywords),2):

    print(f'{keywords[i]} {keywords[i+1]}')

写入文件使用:


with open('out.txt', 'w') as fp:

    for i in range(0,len(keywords),2):

        fp.write(f'{keywords[i]} {keywords[i+1]}\n')


查看完整回答
反对 回复 2023-03-30
?
慕村225694

TA贡献1880条经验 获得超4个赞

尝试这个:


with open('output.txt', 'w') as file:

    for string in keywords:

        file.write(string + '\n')


查看完整回答
反对 回复 2023-03-30
?
波斯汪

TA贡献1811条经验 获得超4个赞

那么你可以print按照你想要的方式,例如:


>>> some_list = [chr(i) for i in range(80,90)]

>>> some_list

['P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']

>>> f = open('somefile.txt', 'w')

>>> print(*some_list, sep='\n', file=f)

>>> f.close()

somefile.txt:


P

Q

R

S

T

U

V

W

X

Y

在您的情况下,它可以是:


keywords = (''.join(i) for i in product(ascii_lowercase, repeat = 2))

with open('output.txt') as f:

    print(*keywords, sep='\n', file=f)


查看完整回答
反对 回复 2023-03-30
  • 6 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信