如何在Python 3中使用input()读取文件

时间:2017-04-20 01:29:39

标签: python python-3.x input

我有一个简单的程序,它查看文件,查找内部的任何数字,并将它们添加到名为running_total的变量中。我的问题似乎是我的文件名正在被读取而不是其内容。

import re

file = input('Enter file name:')
open(file)
print(file)
running_total = None

for line in file:
    line = line.rstrip()
    numbers = re.findall("[0-9]+", line)
    print(numbers)
    for number in numbers:
        running_total += float(number)

print(running_total)

我错过了什么?

3 个答案:

答案 0 :(得分:3)

file是一个表示文件名的字符串,它来自input函数,它仍然是一个字符串。所以当你迭代它时,你会逐个得到文件名的字母。当您调用open(file)时,它返回一个可以迭代的对象来提供文件内容,但您当前没有为该对象提供名称或重新使用它。你的意思是:

file_name = input('Enter file name:')
file_handle = open(file_name)   # this doesn't change file_name, but it does output something new (let's call that file_handle)
for line in file_handle:
    ....
file_handle.close()

...虽然更惯用,Pythonic方式是使用with语句:

file_name = input('Enter file name:')
with open(file_name) as file_handle:
    for line in file_handle:
        ....
# and then you don't have to worry about closing the file at the end (or about whether it has been left open if an exception occurs)

请注意,变量file_handle是一个对象,其类名为file(这是我在此处更改变量名称的原因之一)。

答案 1 :(得分:0)

我认为您希望将运行总计数添加到可添加到的数字中。

然后,您需要获取文件句柄

正则表达式使rstrip不必要

running_total = 0
with open(file) as f: 
    for line in f:
        running_total += sum(float(x) for x in re.findall("[0-9]+", line))
print(running_total)

也在这里

https://stackoverflow.com/a/35592562/2308683

答案 2 :(得分:0)

使用“with open()as”来读取您的文件,因为它应该自动关闭。否则,您需要明确告诉它关闭该文件。

将running_total指定为None会让我犯错误,但是给它一个0值可以解决这个问题。

此外,不要使用正则表达式和剥离线,只需使用isnumeric()。这也删除了你正在使用的第二个for循环,这应该更有效。

file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
print(file)
running_total = 0
for line in file:
    if line.isnumeric():
        running_total += int(line)
print(running_total)

我用txt文件对其进行了测试,该文件包含自己的行数和嵌入在单词中的数字,并且它正确地找到了所有实例。

编辑:我刚刚意识到海报想要总结所有数字,而不是找到所有实例。已将running_total += 1更改为running_total += int(line)

相关问题