如何在 Python 3 中使用 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)

我错过了什么?

原文由 Baruch Elias 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 508
2 个回答

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 (这是我在此处更改变量名称的原因之一)。

原文由 jez 发布,翻译遵循 CC BY-SA 3.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)

原文由 Superspork 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题