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

标签 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)

我错过了什么?

最佳答案

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/

相关文章:

python - 将 `pandas.tslib.Timestamp` 对象转换为 `datetime`

python - 如何防止图像在调整大小时填满整个 Tkinter 窗口?

python - 为什么我的链返回的参数没有部分应用于下一个任务?

python - UnicodeEncodeError : 'utf-8' codec can't encode characters in position 0-15: surrogates not allowed

python - Flask流无法在我的计算机上运行

python - MongoDB 相对于 MySQL 和 PostgreSQL 的优势是什么?

javascript - 为什么我不能通过 javascript 更改文本字段的值?

带有额外字符的python 3打印

C从文件中读取utf字符

c++ - 强大的数字用户输入功能,但零不被视为数字