-2

我有一个.txt包含 100 个 50 位数字的文件。每个数字都在不同的行上。

文件示例:

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
#95 more numbers

我希望能够在打开文件后将每个数字附加到列表中。我怎样才能做到这一点?

我知道如何打开文件:fo = open('file_name', 'r'). 以及如何在最后关闭它:fo.close()

提前致谢!

4

3 回答 3

3

您可以非常轻松地遍历文件中的行:

for line in fo:
    # Do whatever with the line
于 2012-11-18T13:42:14.077 回答
3

Python教程的第7章可以回答这个问题: http: //docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

于 2012-11-18T13:44:44.940 回答
2

这是我能想到的最简单的方法:

with open('numbers.txt') as file:
    lst = [line.strip() for line in file]
于 2012-11-18T13:52:40.493 回答