我无法弄清楚Python程序的读取部分。请协助

时间:2016-06-26 00:38:50

标签: python

写:

def main():

    import random

    #Open a file named numbers.txt.
    myfile = open('numbers.txt', 'w')

    file_size= random.randint(4,7)


    #Produce the numbers
    for i in range(file_size):
        k = random.randrange(5,19,2)



        #Write as many random intergers as the user request in the range of 5-19 on one line
        #to the file.
        myfile.write(str(num) + ' ')

    #Close the file.
    myfile.close()
    print('File Saved')

#Call the main function
main()

阅读:我如何获得读取编码以显示随机数并提供总和?

def main():


    import random

  #Open a file named numbers.txt.
    myfile = open('numbers.txt', 'r')

    #Read/process the file's contents.
    file_contents = myfile.read()
    numbers = file_contents.split(" ")
    odd = 0
    num = int(file_contents)
    for file_contents in numbers:
     odd += num

    #Close the file.
    myfile.close()

    #Print out integer totals

    print('The total of the odd intergers is: ', odd)

1 个答案:

答案 0 :(得分:0)

您希望将每个数字写入文件,因此,您需要将其包含在for循环中:

#Produce the numbers
for count in range(file_size):
    num = random.randrange(5,19,2)
    myfile.write(str(num) + ' ')

在处理数字时,您处于正确的轨道上,但是您已经无序了:

numbers_as_strings = file_contents.split(" ")[:-1]
odd = 0

数字是表示每个数字的字符串列表,我们希望迭代它们并为每个数字做一些事情。您可能想知道我为什么添加[:-1]?因为我们创建了一个像"1 2 3 4 5 "这样的字符串,看到最后一个空格?当您split()时,您将获得"1","2","3","4","5","",而我们不想要最后一个空字符串""

for number_as_string in numbers_as_strings:
    odd += int(number_as_string)

最后,要打印数字列表,有一种很好的方法可以在python join()中内置。 ' '.join()表示将所有这些放在一起,并将空格(' ')放在它们之间。

print(' '.join(numbers_as_strings))