[英]How to read a file with input() in Python 3
我有一个简单的程序,它查看文件,查找内部的任何数字,并将它们添加到名为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()
...虽然更惯用,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
(这是我在此更改变量名称的原因之一)。
我想你会想要将运行总数开始到可以添加的数字。
然后,您需要获取文件句柄
正则表达式使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)
也在这里
使用“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)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.