从python中的文件中的数据制作列表

时间:2013-10-25 09:16:25

标签: python file list python-2.7

我是python的新手,需要帮助从文件中的数据制作列表。该列表包含单独行上的数字(使用“\ n”,这是我不想更改为CSV的内容)。保存的数字量可以随时更改,因为数据保存到文件的方式如下:

计划1:

        # creates a new file for writing
numbersFile = open('numbers.txt', 'w')
    # determines how many times the loop will iterate
totalNumbers = input("How many numbers would you like to save in the file? ")
    # loop to get numbers
count = 0
while count < totalNumbers:
    number = input("Enter a number: ")
        # writes number to file
    numbersFile.write(str(number) + "\n")
    count = count + 1

这是使用该数据的第二个程序。这是一个混乱的部分,我不确定:

计划2:

maxNumbers = input("How many numbers are in the file? ")
numFile = open('numbers.txt', 'r')

total = 0
count = 0
while count < maxNumbers:
    total = total + numbers[count]
    count = count + 1

我想使用从程序1收集的数据来获得程序2中的总数。我想把它放在一个列表中,因为数量可以变化。这是对计算机编程类的介绍,所以我需要一个SIMPLE修复。感谢所有帮助的人。

1 个答案:

答案 0 :(得分:1)

您的第一个程序没问题,但您应该使用raw_input()代替input()(这样也无需在结果上调用str()。)

你的第二个程序有一个小问题:你实际上并没有从文件中读取任何内容。幸运的是,这在Python中很容易。您可以使用

遍历文件中的行
for line in numFile:
    # line now contains the current line, including a trailing \n, if present

因此您根本不需要询问文件中的总数。

如果您想添加数字,请不要忘记首先将字符串line转换为int

total += int(line)       # shorthand for total = total + int(line)

还有一个问题(感谢@tobias_k!):文件的最后一行是空的,int("")会引发错误,所以你可以先检查一下:

for line in numFile:
    if line:
        total += int(line)