5

我想使用列表理解复制以下代码的功能:

with open('file.txt', 'w') as textfile:
    for i in range(1, 6):
        textfile.write(str(i) + '\n')

我尝试了以下方法:

with open('file.txt', 'w') as textfile:
    textfile.write(str([i for i in range(1, 6)]) + '\n')

但它(可以理解)打印[1, 2, 3, 4, 5],而不是单行上的一个数字。

对于“你为什么要这样做?”,我没有答案;我只是想看看有没有可能。谢谢!

编辑:谢谢大家的回复;出于某种原因,我的印象是列表推导总是封装在[].

4

5 回答 5

8

一种方法是file.writelines()

with open('file.txt', 'w') as textfile:
    textfile.writelines(str(i) + "\n" for i in range(1, 6))
于 2013-02-22T02:01:48.303 回答
2
textfile.write('\n'.join(str(i) for i in range(1,6)))

几乎是一样的东西。这将留下一个尾随换行符。如果你需要,你可以这样做:

textfile.write(''.join('{}\n'.format(i) for i in range(1,6)))
于 2013-02-22T02:01:14.833 回答
1

Also, if you're writing text that will be consumable by some other application, more often than not you're writing CSV, and the csv module makes these things easy.

(In this case you only have a single value per line, so this may not be needed.)

import csv

with open("file.txt", "wb") as out_f:
    writer = csv.writer(out_f)
    writer.writerows([[i] for i in range(1, 6)])

NOTE The csv module will take care of converting int to str for you.

于 2013-02-22T02:18:10.500 回答
0

你也可以试试

with open('/tmp/foo.txt','w') as f:
    [f.write(str(i)+' ') for i in range(0,10)]

以@monkut 或@mgilson 为例

于 2013-02-22T03:45:49.797 回答
0

请尝试以下方法:

open('/tmp/foo.txt','w').writelines(f'{i}\n' for i in range(10))
于 2019-06-01T01:15:43.157 回答