Python文件(写/读)

时间:2016-12-06 17:52:39

标签: python

所以我的proffessor已经指示我们用Python编写一个包含这个文件的文件。

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951

然后..我们必须逐行阅读并分别对每一行求和,所以最后它会是这样的......

37107287533902102798797998220837590246510135740250 SUM: 214
46376937677490009712648124896970078050417018260538 SUM: 226
..etc...

需要帮助解决这个问题。

P.S他还将此作为提示添加(lines = f.readlines()) 此外,如果可能的话,尝试帮助一些基本的python,因为我们还是初学者。

1 个答案:

答案 0 :(得分:0)

您最好的解决方案是读取每一行(使用提示的读取行)。请记住,readlines()将为您获取所有行并将它们存储在字符串行列表中。

lines = <filename>.readlines()
# Lines now holds and array of lines read by the file
# lines[0] = 37107287533902102798797998220837590246510135740250 
# lines[1] = 46376937677490009712648124896970078050417018260538 

现在你要添加你的数字行,遍历行中的每个字符,将它转换为数字并运行总数。

# Go through each line
for line in lines:
     total = 0
     # Go through each letter of that line (i.e. 3 then 7 then 1....)
     for letter in line:
          # Cast that letter to a number and add it to the total
          total += int(letter)
     # Append to the end of your line
     line += " SUM " + str(total)

使用python,只需几行即可完成此操作。我会把文件打开给你!