我有一个简单的程序,它浏览一个文件,找到里面的任何数字,并将它们添加到一个名为 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)
我错过了什么?
最佳答案
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()
...尽管更惯用的 Python 方式是使用 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
的对象(这是我在此处更改变量名称的原因之一)。
关于python - 如何在 Python 3 中使用 input() 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43508697/